我有一个存储过程,它将通过复制旧表table1A%yyyymm%
的结构来创建新表table1
。但是在创建新表之前,我需要检查表是否存在,如果存在,我需要先删除表。这是我的存储过程。
DECLARE @yyyymm char(6)
SET @yyyymm=CONVERT(nvarchar(6), GETDATE(), 112)
DECLARE @tableName varchar(50)
SET @tableName='table1A_' + @yyyymm
DECLARE @SQL varchar(max)
SET @SQL = 'DROP TABLE ' + @tableName
IF EXISTS (SELECT * FROM sys.tables WHERE type='u' and name =@tableName)
EXEC(@SQL) print (@sql)
SET @SQL= 'SELECT TOP 0 *
INTO ' + @tableName + ' FROM table1 with (nolock)'
EXEC(@SQL)
但如果表存在,我总会得到如下错误。哪里错了?
DROP TABLE table1A_201404
Msg 2714, Level 16, State 6, Line 1
There is already an object named 'table1A_201404' in the database.
答案 0 :(得分:2)
让我难过......似乎"如果存在"在这种情况下,与exec一起工作不好。更新了下面的脚本:
DECLARE @yyyymm char(6)
SET @yyyymm=CONVERT(nvarchar(6), GETDATE(), 112)
DECLARE @tableName varchar(50)
SET @tableName='table1A_' + @yyyymm
DECLARE @SQL varchar(max)
SET @SQL = 'DROP TABLE ' + @tableName
EXEC('IF EXISTS(SELECT * FROM sys.tables WHERE type=''u'' and name = N''' + @tablename + ''') DROP TABLE table1A_201404')
SET @SQL= 'SELECT TOP 0 *
INTO ' + @tableName + ' FROM sysobjects with (nolock)'
EXEC(@SQL) print @SQL