动态检查 table 是否存在

To check whether the table exists or not dynamically

DECLARE @DROP VARCHAR(MAX)
DECLARE @TAB VARCHAR(MAX)='Employees'
DECLARE @CREATE VARCHAR(MAX)
DECLARE @SELECT VARCHAR(MAX)

--IF OBJECT_ID('DBO.'+@TAB,'U') IS NOT NULL
--BEGIN
IF (EXISTS (SELECT 1 
            FROM INFORMATION_SCHEMA.TABLES 
            WHERE TABLE_SCHEMA = 'dbo' 
              AND TABLE_NAME = @TAB))
BEGIN
    SET @DROP = N'DROP TABLE '+@TAB
    EXEC(@TAB)
END

SET @CREATE= 'CREATE TABLE '+@TAB+
    '(
        ID INT
        ,NAME VARCHAR(50)
        ,PHONE VARCHAR(25)
        ,ADDRESS VARCHAR(100)
    )'

EXEC(@CREATE)
SET @SELECT='SELECT * FROM '+@TAB
EXEC(@SELECT)

我得到一个错误,为什么?

Msg 2809, Level 16, State 1, Line 1
The request for procedure 'Employees' failed because 'Employees' is a table object.

你只犯了一个错误而不是使用 EXEC(@TAB) 你应该使用 EXEC(@DROP)

DECLARE @DROP VARCHAR(MAX)
DECLARE @TAB VARCHAR(MAX)='Employees'
DECLARE @CREATE VARCHAR(MAX)
DECLARE @SELECT VARCHAR(MAX)
--IF OBJECT_ID('DBO.'+@TAB,'U') IS NOT NULL
--BEGIN
IF 
(EXISTS 
    (
    SELECT 
        1 
    FROM INFORMATION_SCHEMA.TABLES 
    WHERE TABLE_SCHEMA = 'dbo' 
    AND  TABLE_NAME = @TAB
    )
)
BEGIN
    SET @DROP=N'DROP TABLE '+@TAB
    print @DROP
    EXEC(@DROP)
END
SET @CREATE=
    'CREATE TABLE '+@TAB+
    '(
        ID INT
        ,NAME VARCHAR(50)
        ,PHONE VARCHAR(25)
        ,ADDRESS VARCHAR(100)
    )'
EXEC(@CREATE)
SET @SELECT='SELECT * FROM '+@TAB
EXEC(@SELECT)

从 SQL Server 2016 SP1 开始,对象可以 DIE - Drop If Exists。因此,对于您的情况,您可以跳过存在性检查,并在动态 SQL 中仅构建以下 T-SQL 语句:

...
'DROP TABLE IF EXISTS ' + @TAB + ';' + 
'CREATE TABLE ' + @TAB + 
...

几乎每个对象都可以DIE,您可以获得更多详细信息here: