复制代码 代码如下:
CREATE PROCEDURE [dbo].[usp_B_DymanicallyAlterStoreProcedure]
AS
DECLARE @VariableList NVARCHAR(MAX) = ''
DECLARE @FieldList NVARCHAR(MAX) = ''
DECLARE @ValueList NVARCHAR(MAX) = ''
DECLARE @FieldValueList NVARCHAR(MAX) = ''
DECLARE @I INT = 1, @R INT = 0
SET @R = (SELECT MAX([Id]) FROM [dbo].[A])
WHILE (@I <= @R)
BEGIN
DECLARE @fName NVARCHAR(100)
IF EXISTS(SELECT [Id] FROM [dbo].[A] WHERE [Id] = @I)
BEGIN
SELECT @fName = [FieldName] FROM [dbo].[A] WHERE [Id] = @I
SET @VariableList = @VariableList + ',@' + @fName +' DECIMAL(18,4)' --动态的字段数据类型都一样
SET @FieldList = @FieldList + ',[' + @fName + ']'
SET @ValueList = @ValueList + ',@' + @fName
SET @FieldValueList = @FieldValueList + ',[' + @fName + '] = @' + @fName
END
SET @I = @I + 1
END
DECLARE @sql_I NVARCHAR(MAX),@sql_U NVARCHAR(MAX)
SET @sql_I = '
ALTER PROCEDURE [dbo].[usp_B_Insert]
(
@ItemCode NVARCHAR(50)
'+ @VariableList +'
)
AS
INSERT INTO [dbo].[B] ([ItemCode]'+ @FieldList +') VALUES (@ItemCode'+ @ValueList +')
'
EXECUTE sp_EXECUTESQL @sql_I;
SET @sql_U = '
ALTER PROCEDURE [dbo].[usp_B_Update]
(
@Id INT,
@ItemCode NVARCHAR(50)
'+ @VariableList +'
)
AS
UPDATE [dbo].[B] SET [ItemCode] = @ItemCode'+ @FieldValueList +' WHERE [Id] = @Id
'
EXECUTE sp_EXECUTESQL @sql_U;
复制代码 代码如下:
CREATE TRIGGER [dbo].[tri_A_Insert] ON [dbo].[A]
FOR INSERT
AS
BEGIN
SET NOCOUNT ON
DECLARE @FieldName NVARCHAR(50)
SELECT @FieldName = [FieldName] FROM INSERTED
EXECUTE('IF NOT EXISTS(SELECT * FROM SYSCOLUMNS WHERE [id] = OBJECT_ID(''B'') AND [name] = '''+ @FieldName +''')
ALTER TABLE [B] ADD ['+ @FieldName +'] DECIMAL(18,4) NULL')
EXECUTE [dbo].[usp_B_DymanicallyAlterStoreProcedure];
END
复制代码 代码如下:
CREATE TRIGGER [dbo].[tri_A_Delete] ON [dbo].[A]
FOR DELETE
AS
BEGIN
SET NOCOUNT ON
DECLARE @FieldName NVARCHAR(50)
SELECT @FieldName = [FieldName] FROM DELETED
EXECUTE('IF EXISTS(SELECT * FROM SYSCOLUMNS WHERE [id] = OBJECT_ID(''B'') AND [name] = '''+ @FieldName +''')
ALTER TABLE [B] DROP COLUMN ['+ @FieldName +']')
EXECUTE [dbo].[usp_B_DymanicallyAlterStoreProcedure];
END
新闻热点
疑难解答