加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

sql清空表数据后重新添加数据存储过程的示例

发布时间:2020-12-12 09:24:02 所属栏目:MsSql教程 来源:网络整理
导读:代码如下:ALTER PROCEDURE [dbo].[sp_add_Jurisdiction] @CTableName varchar(20),--当前要删除、新增的表 @filedkeyValue varchar(20),--要删除的字段值 @filedName varchar(20),--要删除的字段名 @filedNameAdd1 varchar(20),--要新增的字段名1 @filedName

代码如下:ALTER PROCEDURE [dbo].[sp_add_Jurisdiction]
@CTableName varchar(20),--当前要删除、新增的表
@filedkeyValue varchar(20),--要删除的字段值
@filedName varchar(20),--要删除的字段名
@filedNameAdd1 varchar(20),--要新增的字段名1
@filedNameAdd2 varchar(20),--要新增的字段名2
@sql varchar(6000) --新增值字符串,如:25,30;25,31
AS
begin
declare @strSQL_1 varchar(6000) -- 删除
declare @strSQL_2 varchar(6000) -- 新增
BEGIN try
BEGIN TRANSACTION
set @strSQL_1 = 'delete from ['+@CTableName+'] where '+@filedName+' = '+@filedkeyValue+''
exec(@strSQL_1)

DECLARE @Run bit --继续循环的标志
declare @dotIndex as int
declare @doIndex as int
declare @strValue1 as varchar(100)
declare @strValue2 as varchar(100)
declare @strText as varchar(100)
declare @ReturnValue int
set @Run = 1
set @ReturnValue=0;
while( @Run = 1)
begin
if(len(@sql)>0) --如果字符串还不为空,则进行一下操作
begin
set @dotIndex=CharIndex(';',@sql)
if(@dotIndex = 0) --判断是否找到了';'符号
begin
set @doIndex=CharIndex(',',@sql)
set @strValue1 = substring(@sql,1,@doIndex-1)
set @strValue2 = substring(@sql,@doIndex+1,LEN(@sql))
set @strSQL_2 = 'insert into ['+@CTableName+'] ('+@filedName+','+@filedNameAdd1+','+@filedNameAdd2+') values ('+@filedkeyValue+','+@strValue1+','+@strValue2+')'
exec(@strSQL_2);
set @ReturnValue=@ReturnValue+1;
set @Run=0
end;
else
begin
set @strText = substring(@sql,@dotIndex-1) --截取','前的字符串
set @sql=substring(@sql,@dotIndex+1,len(@sql)) --把字符串的长度缩短至后一个
set @doIndex=CharIndex(',@strText)
set @strValue1 = substring(@strText,@doIndex-1)
set @strValue2 = substring(@strText,LEN(@strText))
set @strSQL_2 = 'insert into ['+@CTableName+'] ('+@filedName+','+@strValue2+')'
exec(@strSQL_2)
set @ReturnValue=@ReturnValue+1;
end
end
else
begin
set @Run=0
set @ReturnValue=@ReturnValue+1;
end
end
Commit Transaction
return @ReturnValue;
end try
begin catch
set @ReturnValue=0;
Rollback Transaction
return @ReturnValue;
end catch
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读