Sql-Server

更新所有包含列名的表

  • June 30, 2016

在 SQL Server 中,我可以找到所有包含 a 的表COLUMN_NAME

SELECT *
FROM   INFORMATION_SCHEMA.columns
WHERE  COLUMN_NAME = 'COLUMN_NAME'

如何更新所有這些列,例如:

UPDATE <table> SET <column_name> = 123

該解決方案需要在 SQL Server 2012 及更高版本中執行。在我的情況下,該列將始終是相同的數據類型:bigint

我需要使用 aCURSOR或類似的嗎?

此查詢將為您提供表名列表和臨時表中的欄位名。

IF OBJECT_ID('tempdb..#BaseData') IS NOT NULL DROP TABLE #BaseData
GO
CREATE TABLE #BaseData (Schema_Name sysname, Table_Name sysname, Field_Name sysname, SQLScript varchar(max));

DECLARE @FieldName varchar(20); SET @FieldName = 'COLUMN_NAME';

INSERT INTO #BaseData (Schema_Name, Table_Name, Field_Name, SQLScript)
SELECT
s.name
,o.name 
,c.name
,'ALTER TABLE ' + s.name + '.' + o.name + ' SET ' + c.name + ' = ''123'''
FROM sys.columns c
JOIN sys.types t
   ON c.user_type_id = t.user_type_id
JOIN sys.objects o
   ON c.object_id = o.object_id
JOIN sys.schemas s ON o.schema_id=s.schema_id
WHERE c.name LIKE @FieldName 
   AND o.type_desc = 'USER_TABLE';
   SELECT * FROM #BaseData

結果將如下所示。前三列並非完全必要,但我將它們包括在內是為了展示數據是如何組合在一起的;

Schema_Name Table_Name  Field_Name    SQLScript
dbo         Table1      Column_Name   ALTER TABLE dbo.Table1 SET Column_Name = '123'
dbo         Table2      Column_Name   ALTER TABLE dbo.Table2 SET Column_Name = '123'
dbo         Table3      Column_Name   ALTER TABLE dbo.Table3 SET Column_Name = '123'
dbo         Table4      Column_Name   ALTER TABLE dbo.Table4 SET Column_Name = '123'

然後,您可以使用游標執行數據的每一行;

DECLARE @sql VARCHAR(MAX)
DECLARE @SqlScript VARCHAR(max)

DECLARE c CURSOR LOCAL FAST_FORWARD FOR
   SELECT SQLScript
   FROM #BaseData;
OPEN c;
FETCH NEXT FROM c INTO @SQLScript;

WHILE @@FETCH_STATUS = 0
BEGIN
   SET @sql = @SqlScript

   EXEC(@sql); 

   FETCH NEXT FROM c INTO @SQLScript;
END

CLOSE c;
DEALLOCATE c;

這將執行您之前創建的每一行程式碼。上面的範常式式碼將更新所有表,以便 Column_Name = ‘123’

引用自:https://dba.stackexchange.com/questions/142676