下面这篇《​​动态为表添加存储时间字段​​》添加字段,只能添加时间类型的字段。想把这个方法改良一下,尽量能做到通用。

动态为表添加字段_EXISTS

 


动态为表添加字段_EXISTS_02动态为表添加字段_EXISTS_03


SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author: Insus.NET
-- Blog:
-- Create date: 2019-05-29
-- Update date: 2019-05-29
-- Description: 动态为表添加字段
-- =============================================
CREATE PROCEDURE [dbo].[usp_DyanmicallyAddColumn]
(
@TABLE_CATALOG SYSNAME,
@TABLE_SCHEMA SYSNAME,
@TABLE_NAME SYSNAME,
@COLUMN_NAME SYSNAME,
@DATATYPE SYSNAME
)
AS
BEGIN
IF NOT EXISTS(SELECT TOP 1 1 FROM [tempdb].[sys].[columns] WHERE object_id = object_id(@TABLE_CATALOG + N'.'+ @TABLE_SCHEMA + N'.' + @TABLE_NAME) AND [name] = @COLUMN_NAME)
OR NOT EXISTS(SELECT TOP 1 1 FROM [sys].[columns] WHERE object_id = object_id(@TABLE_CATALOG + N'.'+ @TABLE_SCHEMA + N'.' + @TABLE_NAME) AND [name] = @COLUMN_NAME)
EXECUTE('ALTER TABLE '+ @TABLE_NAME +' ADD '+ @COLUMN_NAME +' ' + @DATATYPE +'')
END
GO

Source Code

 

举例使用:

动态为表添加字段_sys_04