我是一名新的SQL开发人员,我正在尝试编写一个存储过程,从我的数据库系统视图中选择,我需要获得以下结果:
我想选择我的
示例结果:
Database Table Schema Primary Key Identity
-------------------------------------------------------------
DB1 Table1 dbo None No Identity
DB1 Table2 dbo abcID abcID
我有我的功能(见下),但我在使用它的问题上遇到了问题。我也有问题让我的CASE陈述正确。
到目前为止,这是我的脚本:
CREATE PROC System_Views_Databases_Without_Primary_Keys
@DBName NVARCHAR(255)
AS
SET NOCOUNT ON;
SELECT
db_name () AS [Database],
SCHEMA_NAME(SCHEMA_ID) AS [Schema],
tab.Name AS [Table],
tc.TABLE_NAME AS [Primary Key],
col.is.identity AS [Identity]
FROM
sys.columns col
JOIN
sys.tables tab ON col.object_id = tab.object_id
JOIN
INFORMATION_SCHEMA.TABLE_CONSTRAINTS tc ON tab.name = tc.table_name
WHERE
OBJECTPROPERTY(tab.object_id, 'TableHasPrimaryKey') = 1
CASE
WHEN [Identity] = 1 THEN 'Yes Identity'
WHEN [Identity] = 0 THEN 'No Identity'
END
我的DDL功能:
CREATE FUNCTION [dbo].[Primary_Key] (@Primary_Key VARCHAR(255))
RETURNS VARCHAR (255)
AS
BEGIN
DECLARE @nonvalid varchar (255)
IF @Primary_Key IS NULL
SET @nonvalid = 'None'
ELSE
SET @nonvalid = @Primary_Key
RETURN @nonvalid
END
非常感谢任何帮助!
答案 0 :(得分:0)
试试这个,它会给你表中的每一列,并告诉哪一个是身份,哪一个是主键。
SELECT DISTINCT
db_name () AS [Database],
SCHEMA_NAME(SCHEMA_ID) AS [Schema],
tab.Name AS [Table],
col.name,
Case when COLUMNPROPERTY(OBJECT_ID(tab.name),col.name,'isidentity') = 1 then col.name Else 'No Identity' End AS [Identity]
,Case when Prim.CONSTRAINT_NAME is not null then prim.CONSTRAINT_NAME else 'None' End as Primarykey
FROM
sys.columns col
JOIN
sys.tables tab
ON col.object_id = tab.object_id
Left JOIN (
SELECT K.TABLE_NAME,
K.COLUMN_NAME,
K.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS AS C
JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE AS K
ON C.TABLE_NAME = K.TABLE_NAME
AND C.CONSTRAINT_CATALOG = K.CONSTRAINT_CATALOG
AND C.CONSTRAINT_SCHEMA = K.CONSTRAINT_SCHEMA
AND C.CONSTRAINT_NAME = K.CONSTRAINT_NAME
WHERE C.CONSTRAINT_TYPE = 'PRIMARY KEY'
) prim
on prim.TABLE_NAME = tab.name and prim.column_name=col.name