T SQL variable showing incorrect syntax

Advertisements
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

>Solution :

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.

Leave a Reply Cancel reply