- SET ANSI_NULLS ON
- GO
- SET QUOTED_IDENTIFIER ON
- GO
-
- -- =============================================
- -- Author: Insus.NET
- -- Blog: https://insus.cnblogs.com
- -- Create date: 2019-05-29
- -- Update date: 2019-05-29
- -- Description: 动态为表添加存储时间字段
- -- =============================================
- CREATE PROCEDURE [dbo].[usp_DyanmicallyAddStorageDatetimeField]
- (
- @TABLE_CATALOG SYSNAME,
- @TABLE_SCHEMA SYSNAME,
- @TABLE_NAME SYSNAME,
- @COLUMNs NVARCHAR(MAX) -- '[column1],[column2],[column3]...'
- )
- AS
- BEGIN
- DECLARE @source TABLE ([ID] INT IDENTITY(1,1), [value] NVARCHAR(MAX))
- INSERT INTO @source ([value]) SELECT [value] FROM [dbo].[tvf_ConvertStringToTable](@COLUMNs,',')
- DECLARE @r INT = 1,@rs INT = 0
- SELECT @rs = MAX([ID]) FROM @source
-
- WHILE @r <= @rs
- BEGIN
- DECLARE @COLUMN_NAME SYSNAME
- SELECT @COLUMN_NAME = CONVERT(VARCHAR(30), [value], 23) FROM @source WHERE [ID] = @r
-
- EXECUTE('IF [dbo].[usp_IsExistsColumn]('''+ @TABLE_CATALOG +''','''+ @TABLE_SCHEMA +''','''+ @TABLE_NAME +''','''+ @COLUMN_NAME +''') = 0 ALTER TABLE '+ @TABLE_NAME +' ADD '+ @COLUMN_NAME +' DATETIME')
- SET @r= @r + 1
- END
- END