2

我正在尝试一次更改多个 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

有人能指出我哪里出错了吗?

4

2 回答 2

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;
于 2012-07-12T16:39:42.403 回答
1

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

EXEC (@SQL);
于 2012-07-12T16:42:01.210 回答