Scenario:
Sometime we have requirement that add column in all the tables in Database. Today we have to add CreatedOn column in all the tables if it does not exist in table already.Solution:
We will be using Cursor to perform this operation.Please provide Column name and Data Type for these variables. In below example I am adding CreatedOn column with DateTime data type.
SET @COLUMN_NAME='ColumnNameYouWantToAdd'
SET @COLUMN_DATATYPE='DataTypeOfColumn'
------------------------------------------------Code---------------------------------------------------
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)
Very Helpful! Saved me hours of work.
ReplyDeleteThank you
ReplyDeleteMua vé máy bay tại Aivivu, tham khảo
ReplyDeletevé máy bay đi Mỹ Vietnam Airline
ve may bay từ mỹ về việt nam hãng eva
bay nhật bản việt nam
ve may bay tư duc ve viet nam
ve may bay tu canada ve viet nam
khi nào mở lại đường bay hàn quốc
khách sạn cách ly ở tây ninh
Awesome !!!! Great work brother
ReplyDelete