比较SQL中的单个值以标识候选键

时间:2017-01-04 15:40:39

标签: sql sql-server tsql

我需要检查列是否是候选键。为了使它成为通用的,我创建了一个存储过程:

ALTER PROCEDURE [dbo].[CheckPK] 
(
    @tableName VARCHAR(100),
    @pk VARCHAR(100)
)
AS
PRINT 'Checking for candidate key ' + @pk + ' for table: ' + @tableName

DECLARE @sql NVARCHAR(4000)

SET @sql = 'select count(distinct ([' + @pk + '])) as tot_pk from ' + @tableName + ' select count (*) as tot_real from ' + @tableName

EXEC sp_executesql @sql

哪个工作正常。我要做的是验证两个选定的值是否相同。

问题:是否可以添加if(tot_pk = tot_real)类型的条件?

我是SQL的新手,所以如果这个问题看似微不足道,我道歉。谢谢

1 个答案:

答案 0 :(得分:0)

试试这段代码。也许是你需要的。

我添加了一个可选参数@Schema

<强> CODE

--EXEC [dbo].[CheckPK] 'name of table','name of column', 'schema is optional'

ALTER PROCEDURE [dbo].[CheckPK] 
(
    @tableName VARCHAR(100)
    , @pk VARCHAR(100)
    , @Schema VARCHAR(100) = NULL
)
AS
BEGIN
    BEGIN TRY
        PRINT 'Checking primary key ' + @pk + ' for table: ' + @tableName

        DECLARE @sql NVARCHAR(4000)

        SET @sql = 'select count(distinct ([' + @pk + '])) as tot_pk from '
+ ISNULL(@Schema + '.', '') + @tableName + ' select count (*) as tot_real from ' + ISNULL(@Schema + '.', '') + @tableName

        EXEC sp_executesql @sql

        IF EXISTS (
            SELECT COLUMN_NAME
            FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
            WHERE OBJECTPROPERTY(OBJECT_ID(CONSTRAINT_SCHEMA + '.' + CONSTRAINT_NAME), 'IsPrimaryKey') = 1
                AND TABLE_NAME = @tableName
                AND TABLE_SCHEMA = ISNULL(@Schema, TABLE_SCHEMA)
                AND COLUMN_NAME = @pk
            )
           SELECT @pk + ' IS A PRYMARY KEY'
       ELSE
           SELECT @pk + ' IS NOT A PRYMARY KEY'
   END TRY

   BEGIN CATCH
       SELECT 'An error has occurred. Verify that ''' + @tableName + ''' it is a table and has the correct schema and ''' + @pk + ''' is a valid column of the table'
   END CATCH
END