sql >> Base de Datos >  >> RDS >> Sqlserver

Devolver claves principales de un servidor vinculado en SQL Server (ejemplos de T-SQL)

En SQL Server puede usar sp_primarykeys procedimiento almacenado del sistema para devolver las columnas de clave principal de un servidor vinculado especificado. Devuelve una fila por columna clave, para la tabla remota especificada.

La forma más sencilla de ejecutar este procedimiento almacenado es pasar el nombre del servidor vinculado. Hacer eso devolverá todas las claves principales de la base de datos predeterminada en el servidor vinculado especificado.

También tiene la opción de especificar una base de datos diferente y/o un esquema de tabla específico.

Sintaxis

La sintaxis es así:

sp_primarykeys [ @table_server = ] 'table_server'   
     [ , [ @table_name = ] 'table_name' ]   
     [ , [ @table_schema = ] 'table_schema' ]   
     [ , [ @table_catalog = ] 'table_catalog' ]

El @table_server argumento es el único argumento requerido. Este es el nombre del servidor vinculado del que desea obtener la información de la clave principal.

Los otros argumentos son opcionales.

Ejemplo 1:devolver todas las claves principales en la base de datos predeterminada

El siguiente ejemplo devuelve todas las claves principales de la base de datos predeterminada en el servidor vinculado llamado Homer.

EXEC sp_primarykeys @table_server = 'Homer';

También se puede ejecutar así:

EXEC sp_primarykeys 'Homer';

Resultado:

+-------------+---------------+--------------+---------------+-----------+-----------+
| TABLE_CAT   | TABLE_SCHEM   | TABLE_NAME   | COLUMN_NAME   | KEY_SEQ   | PK_NAME   |
|-------------+---------------+--------------+---------------+-----------+-----------|
| Music       | dbo           | Albums       | AlbumId       | 1         | NULL      |
| Music       | dbo           | Artists      | ArtistId      | 1         | NULL      |
| Music       | dbo           | Country      | CountryId     | 1         | NULL      |
| Music       | dbo           | Genres       | GenreId       | 1         | NULL      |
+-------------+---------------+--------------+---------------+-----------+-----------+

En este caso, hay cuatro columnas de clave principal (se enumeran en COLUMN_NAME ). Notarás que el PK_NAME la columna es NULL . Esta columna es para el identificador de clave principal. Microsoft afirma que esto devuelve NULL si no se aplica a la fuente de datos.

El KEY_SEQ columna es el número de secuencia de la columna en una clave principal de varias columnas. En este caso, no había claves principales de varias columnas, por lo que el valor es 1 para cada clave principal. El siguiente ejemplo devuelve algunos resultados con claves principales de varias columnas.

Ejemplo 2:especificar una base de datos diferente

El siguiente ejemplo especifica que WideWorldImportersDW se debe utilizar la base de datos.

EXEC sp_primarykeys 
  @table_server = 'Homer',   
  @table_catalog = 'WideWorldImportersDW';

Resultado:

+----------------------+---------------+-------------------------+------------------------------+-----------+-----------+
| TABLE_CAT            | TABLE_SCHEM   | TABLE_NAME              | COLUMN_NAME                  | KEY_SEQ   | PK_NAME   |
|----------------------+---------------+-------------------------+------------------------------+-----------+-----------|
| WideWorldImportersDW | Dimension     | City                    | City Key                     | 1         | NULL      |
| WideWorldImportersDW | Dimension     | Customer                | Customer Key                 | 1         | NULL      |
| WideWorldImportersDW | Dimension     | Date                    | Date                         | 1         | NULL      |
| WideWorldImportersDW | Dimension     | Employee                | Employee Key                 | 1         | NULL      |
| WideWorldImportersDW | Dimension     | Payment Method          | Payment Method Key           | 1         | NULL      |
| WideWorldImportersDW | Dimension     | Stock Item              | Stock Item Key               | 1         | NULL      |
| WideWorldImportersDW | Dimension     | Supplier                | Supplier Key                 | 1         | NULL      |
| WideWorldImportersDW | Dimension     | Transaction Type        | Transaction Type Key         | 1         | NULL      |
| WideWorldImportersDW | Fact          | Movement                | Movement Key                 | 1         | NULL      |
| WideWorldImportersDW | Fact          | Movement                | Date Key                     | 2         | NULL      |
| WideWorldImportersDW | Fact          | Order                   | Order Key                    | 1         | NULL      |
| WideWorldImportersDW | Fact          | Order                   | Order Date Key               | 2         | NULL      |
| WideWorldImportersDW | Fact          | Purchase                | Purchase Key                 | 1         | NULL      |
| WideWorldImportersDW | Fact          | Purchase                | Date Key                     | 2         | NULL      |
| WideWorldImportersDW | Fact          | Sale                    | Sale Key                     | 1         | NULL      |
| WideWorldImportersDW | Fact          | Sale                    | Invoice Date Key             | 2         | NULL      |
| WideWorldImportersDW | Fact          | Stock Holding           | Stock Holding Key            | 1         | NULL      |
| WideWorldImportersDW | Fact          | Transaction             | Transaction Key              | 1         | NULL      |
| WideWorldImportersDW | Fact          | Transaction             | Date Key                     | 2         | NULL      |
| WideWorldImportersDW | Integration   | City_Staging            | City Staging Key             | 1         | NULL      |
| WideWorldImportersDW | Integration   | Customer_Staging        | Customer Staging Key         | 1         | NULL      |
| WideWorldImportersDW | Integration   | Employee_Staging        | Employee Staging Key         | 1         | NULL      |
| WideWorldImportersDW | Integration   | ETL Cutoff              | Table Name                   | 1         | NULL      |
| WideWorldImportersDW | Integration   | Lineage                 | Lineage Key                  | 1         | NULL      |
| WideWorldImportersDW | Integration   | Movement_Staging        | Movement Staging Key         | 1         | NULL      |
| WideWorldImportersDW | Integration   | Order_Staging           | Order Staging Key            | 1         | NULL      |
| WideWorldImportersDW | Integration   | PaymentMethod_Staging   | Payment Method Staging Key   | 1         | NULL      |
| WideWorldImportersDW | Integration   | Purchase_Staging        | Purchase Staging Key         | 1         | NULL      |
| WideWorldImportersDW | Integration   | Sale_Staging            | Sale Staging Key             | 1         | NULL      |
| WideWorldImportersDW | Integration   | StockHolding_Staging    | Stock Holding Staging Key    | 1         | NULL      |
| WideWorldImportersDW | Integration   | StockItem_Staging       | Stock Item Staging Key       | 1         | NULL      |
| WideWorldImportersDW | Integration   | Supplier_Staging        | Supplier Staging Key         | 1         | NULL      |
| WideWorldImportersDW | Integration   | Transaction_Staging     | Transaction Staging Key      | 1         | NULL      |
| WideWorldImportersDW | Integration   | TransactionType_Staging | Transaction Type Staging Key | 1         | NULL      |
+----------------------+---------------+-------------------------+------------------------------+-----------+-----------+

Ejemplo 3:especificar un esquema de tabla

El siguiente ejemplo limita los resultados a un esquema de tabla específico.

EXEC sp_primarykeys 
  @table_server = 'Homer',
  @table_schema = 'Fact',
  @table_catalog = 'WideWorldImportersDW';

Resultados:

+----------------------+---------------+---------------+-------------------+-----------+-----------+
| TABLE_CAT            | TABLE_SCHEM   | TABLE_NAME    | COLUMN_NAME       | KEY_SEQ   | PK_NAME   |
|----------------------+---------------+---------------+-------------------+-----------+-----------|
| WideWorldImportersDW | Fact          | Movement      | Movement Key      | 1         | NULL      |
| WideWorldImportersDW | Fact          | Movement      | Date Key          | 2         | NULL      |
| WideWorldImportersDW | Fact          | Order         | Order Key         | 1         | NULL      |
| WideWorldImportersDW | Fact          | Order         | Order Date Key    | 2         | NULL      |
| WideWorldImportersDW | Fact          | Purchase      | Purchase Key      | 1         | NULL      |
| WideWorldImportersDW | Fact          | Purchase      | Date Key          | 2         | NULL      |
| WideWorldImportersDW | Fact          | Sale          | Sale Key          | 1         | NULL      |
| WideWorldImportersDW | Fact          | Sale          | Invoice Date Key  | 2         | NULL      |
| WideWorldImportersDW | Fact          | Stock Holding | Stock Holding Key | 1         | NULL      |
| WideWorldImportersDW | Fact          | Transaction   | Transaction Key   | 1         | NULL      |
| WideWorldImportersDW | Fact          | Transaction   | Date Key          | 2         | NULL      |
+----------------------+---------------+---------------+-------------------+-----------+-----------+