0

I need to check if a column is candidate key. To make it generic, I created a stored procedure:

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

Which works fine. What I have to do is verify that the two selected values are the same.

QUESTION: is it possible to add an if(tot_pk = tot_real) type of condition?

I am a newbie in SQL, so I apologise if this question seems trivial. Thank you

RBarryYoung
  • 55,398
  • 14
  • 96
  • 137
Nic
  • 1,262
  • 2
  • 22
  • 42

1 Answers1

0

Try this code. Maybe is that you need.

I added an optional parameter @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
JotaPardo
  • 817
  • 9
  • 27