问题
I'm trying to alter multiple SQL Server 2008 R2 tables at one time.
This is my code:
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
I can't get this to work to save my life and get the following error:
Lookup Error - SQL Server Database Error: The name 'ALTER TABLE dbo.PM1GTVLV ADD [identityID] bigint IDENTITY(1, 1) NOT NULL ' is not a valid identifier.
I've also tried multiple string variations and using sp_executesql
as well.
Can someone point out where I've gone wrong?
回答1:
Try
DECLARE @SQL NVARCHAR(MAX);
EXEC sp_executesql @SQL;
Instead of EXEC @sql.
As an aside, this is a much more usable version of the same code IMHO:
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;
Or even better:
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;
回答2:
To execute a character string, EXEC
requires parenthesis around the string (or character variable) as shown in the BOL syntax:
EXEC (@SQL);
来源:https://stackoverflow.com/questions/11456523/altering-multiple-tables-at-once