一次更改多个表

时间:2012-07-12 16:37:49

标签: tsql sql-server-2008-r2 dynamic-sql

我正在尝试一次更改多个SQL Server 2008 R2表。

这是我的代码:

use DatabaseName
go

Declare @SchemaUsed varchar(20) = 'dbo'

create table #Tables
(
  TableName varchar(100), Processed int
)

insert into #Tables 
  select top 1 table_name, 0  
  from INFORMATION_SCHEMA.TABLES 
  where TABLE_SCHEMA = @SchemaUsed
  and table_type = 'Base Table'
  and (TABLE_NAME like 'PM%' )
  ORDER BY TABLE_NAME

DECLARE @TableName varchar(max)
DECLARE @SQL varchar(max)

WHILE EXISTS (select top 1 'x' from #Tables where Processed = 0)
BEGIN
    SET @TableName = (select top 1 TableName from #Tables where Processed = 0)

  Set @SQL = 'ALTER TABLE ' + @SchemaUsed + '.' + @TableName + ' ADD [identityID]  bigint IDENTITY(1, 1) NOT NULL '
 -- Set @SQL =     '''' + @SQL + ''''
  Print @SQL
 EXEC  @SQL;

    update #Tables
    set Processed = 1
    where TableName = @TableName
END

drop table #Tables

我无法通过这项工作来挽救我的生命并收到以下错误:

  

查找错误 - SQL Server数据库错误:名称'ALTER TABLE   dbo.PM1GTVLV ADD [identityID] bigint IDENTITY(1,1)NOT NULL'不是   有效的标识符。

我也尝试了多个字符串变体并使用sp_executesql

有人可以指出我出错的地方吗?

2 个答案:

答案 0 :(得分:3)

尝试

DECLARE @SQL NVARCHAR(MAX);

EXEC sp_executesql @SQL;

而不是EXEC @sql。

顺便说一句,这是相同代码恕我直言的更实用的版本:

DECLARE @SchemaUsed VARCHAR(20) = 'dbo';

DECLARE @sql NVARCHAR(MAX) = N'';

SELECT @sql += CHAR(13) + CHAR(10) + N'ALTER TABLE ' 
 + QUOTENAME(@SchemaUsed) + '.'
 + QUOTENAME(name) + ' ADD [identityID]
   BIGINT IDENTITY(1,1) NOT NULL;'
FROM sys.tables
WHERE SCHEMA_NAME([schema_id]) = @SchemaUsed
AND name LIKE 'PM%';

PRINT @sql;

--EXEC sp_executesql @sql;

甚至更好:

DECLARE @SchemaUsed VARCHAR(20) = 'dbo';

DECLARE @sql NVARCHAR(MAX) = N'';

SELECT @sql += CHAR(13) + CHAR(10) + N'ALTER TABLE ' 
 + QUOTENAME(@SchemaUsed) + '.'
 + QUOTENAME(name) + ' ADD [identityID]
   BIGINT IDENTITY(1,1) NOT NULL;'
FROM sys.tables AS t
WHERE SCHEMA_NAME([schema_id]) = @SchemaUsed
AND name LIKE 'PM%'
AND NOT EXISTS (SELECT 1 FROM sys.columns AS c
 WHERE [object_id] = t.[object_id]
 AND c.is_identity = 1);

PRINT @sql;

--EXEC sp_executesql @sql;

答案 1 :(得分:1)

要执行字符串,EXEC需要在字符串(或字符变量)周围加括号,如BOL syntax所示:

EXEC (@SQL);