SQL Server T SQL variable showing incorrect syntax [duplicate]

3phpmpom  于 2023-02-28  发布在  其他
关注(0)|答案(1)|浏览(142)

This question already has answers here:

A table name as a variable (10 answers)
Closed 5 days ago.

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

hs1ihplo

hs1ihplo1#

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.

相关问题