-1
DECLARE @tablename VARCHAR(100) = 'House';


IF OBJECT_ID(@tablename, N'U') IS NOT NULL
BEGIN
    IF EXISTS(SELECT 1 FROM @tablename)
    BEGIN
        PRINT 'Table already exists and has data, not dropping it.'
    END
    ELSE
    BEGIN
        DROP TABLE @tablename
        PRINT 'Table dropped successfully.'
    END
END
ELSE
BEGIN
    PRINT 'Table does not exist.'
END

Please correct it for SQL Server

juergen d
  • 201,996
  • 37
  • 293
  • 362
Nothing
  • 13
  • 3

1 Answers1

0

You can try this:

DECLARE @tablename NVARCHAR(128) = 'House';


IF OBJECT_ID(@tablename, N'U') IS NOT NULL
BEGIN

    DECLARE @DynamicTSQLStatement NVARCHAR(MAX);

    SET @DynamicTSQLStatement = N'

    IF EXISTS(SELECT 1 FROM ' + @tablename + ')
    BEGIN
        PRINT ''Table already exists and has data, not dropping it.''
    END
    ELSE
    BEGIN
        DROP TABLE ' + @tablename + '
        PRINT ''Table dropped successfully.''
    END

    ';

    EXEC sp_executesql @DynamicTSQLStatement;

END
ELSE
BEGIN
    PRINT 'Table does not exist.'
END

Also, it would be better to pass and the schema of the table.

gotqn
  • 42,737
  • 46
  • 157
  • 243