试试这个——
DECLARE @SQL NVARCHAR(MAX)
SELECT @SQL = STUFF((
SELECT CHAR(13) + 'ALTER TABLE [' + s.name + '].[' + o.name + ']
ADD [InsertedOn] DATETIME NOT NULL CONSTRAINT [DF_' + o.name + '_InsertedOn] DEFAULT GETDATE()'
FROM sys.objects o WITH (NOWAIT)
JOIN sys.schemas s WITH (NOWAIT) ON o.[schema_id] = s.[schema_id]
WHERE NOT EXISTS(
SELECT 1
FROM sys.columns c WITH (NOWAIT)
WHERE c.[object_id] = o.[object_id]
AND c.name = 'InsertedOn'
)
AND o.[type] = 'U'
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
PRINT @SQL
EXEC sys.sp_executesql @SQL
输出 -
ALTER TABLE [tt].[t1]
ADD [InsertedOn] DATETIME NOT NULL CONSTRAINT [DF_t1_InsertedOn] DEFAULT GETDATE()
ALTER TABLE [tt].[t2]
ADD [InsertedOn] DATETIME NOT NULL CONSTRAINT [DF_t2_InsertedOn] DEFAULT GETDATE()