名站网址导航为大家提供关于数据库教程相关的教程网站知识。
有一个表,用户需要在后台操作办法它,希望能对它动态进行添加删除字段。这个功能也许没有问题,但是它原有插入与更新的两个存储过程,也需要一起修改。因此Insus.NET实现了它,因此此文会让您了解到怎样动态为一个表添加删除字段以及动态修改它的存储过程SQL对时间处理的数据库语句小结
复制具体相关代码 具体相关代码如下:,--获取当前时间 Select getdate() --获取当前年月日 YY代表年,MM代表月,DD代表日,hh代表时,ss代表秒 /* year yy 1753--9999 quarter qq 1
首先需要建一个表[A],这个表只有两个字段,一个是[ID]自动增长,另一个是表[B]的字段名,存储的每一笔记录,即是用户需要操作办法的表[B]的字段。这个表[A]需要建添加,更新,以及删除的存储过程,方便用户在后台方便操作办法,还有重点部分,需要写触发器。如有记录对表[A]进行添加,更新或是删除时,它会触发去作表[B]相应操作办法,还要去修改表[B]的存储过程。
动态修改表[B]的存储过程:
复制具体相关代码 具体相关代码如下:
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;
表[A]的插入触发器:
复制具体相关代码 具体相关代码如下:
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
表[A]删除触发器:
复制具体相关代码 具体相关代码如下:
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