Scenarie:
Nogle gange har vi krav om at tilføje kolonne i alle tabellerne i databasen. I dag skal vi tilføje CreatedOn-kolonnen i alle tabellerne, hvis den ikke allerede findes i tabellen.Løsning:
Vi vil bruge markøren til at udføre denne handling.Angiv venligst kolonnenavn og datatype for disse variable. I eksemplet nedenfor tilføjer jeg CreatedOn-kolonnen med DateTime-datatypen.
SET @COLUMN_NAME='ColumnNameYouWantToAdd'
SET @COLUMN_DATATYPE='DataTypeOfColumn'
---------------------------------------------- --Kode----------------------------------------------- ----
USE TESTDB GO
--Declare Variables
DECLARE @TableName VARCHAR(100)
DECLARE @TableSchema VARCHAR(100)
DECLARE @COLUMN_NAME VARCHAR(50)
SET @COLUMN_NAME='CreatedOn' -- Change Column Name according to your requirement
DECLARE @COLUMN_DATATYPE VARCHAR(50)
SET @COLUMN_DATATYPE='DateTime' -- Provide data type for column --Declare Cursor
DECLARE CUR CURSOR FOR SELECT TABLE_SCHEMA, TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' --OPEN CURSOR
OPEN CUR
--Fetch First Row
FETCH NEXT FROM CUR INTO @TableSchema,@TableName --Loop
WHILE @@FETCH_STATUS = 0 BEGIN DECLARE @SQL NVARCHAR(MAX) SET @SQL=NULL IF NOT EXISTS ( SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME=@TableName AND COLUMN_NAME=@COLUMN_NAME
and Table_Schema=@TableSchema) BEGIN SET @SQL='ALTER TABLE '+@TableSchema+'.'+@TableName +' ADD '+@COLUMN_NAME
+ ' '+@COLUMN_DATATYPE PRINT @SQL EXEC ( @SQL) END IF EXISTS ( SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME=@TableName AND COLUMN_NAME=@COLUMN_NAME
and Table_Schema=@TableSchema) BEGIN PRINT 'Column Already exists in Table' END FETCH NEXT FROM CUR INTO @TableSchema,@TableName END --Close and Deallocate Cursor
CLOSE CUR
DEALLOCATE CUR
Video Demo: How to Add Column to all the Tables in SQL Server Database (Cursor Example)