mssql字符串分割后的值,把表中不存在的插入表中

字符串分割后的值,把表中不存在的插入表中 --供大家参考

使用场景,自行思考……

--创建表tb1
Create table tb1
(
cola int,
colb varchar(50)
)
--插入数据
insert into tb1(cola,colb)
select 1, 'A' union all
select 2, 'B' union all
select 3, 'C';
--存储过程
Create proc sp_tbTest
@sid int,--ID
@str varchar(20)--A,B,C,D,G
AS
BEGIN
insert into tb1(cola,colb) select @sid ,sp from [dbo].[split](@str,',')
where sp not in (select colb from tb1 where cola=@sid)
END
exec sp_tbTest 4,'D,G,A,B,C';--表中已近存在了A,B,C,执行存储过程的话,本次插入的是D,G
select * from tb1

--实现分割的函数

ALTER function [dbo].[split](@SourceSql varchar(8000),@Code varchar(10))
returns @temp table(sp varchar(1000))
--实现split功能 的函数
--date :2007-7-10
--Author :sp
as
begin
declare @i int
set @SourceSql=rtrim(ltrim(@SourceSql))
set @i=charindex(@Code,@SourceSql)
while @i>=1
begin
insert @temp values(left(@SourceSql,@i-1))
set @SourceSql=substring(@SourceSql,@i+1,len(@SourceSql)-@i)
set @i=charindex(@Code,@SourceSql)
end
if @SourceSql<>'/'
insert @temp values(@SourceSql)
return
end

--以下是朋友Lewis写的案例;没有用到自定义的split函数,而是直接在存储过程中分割字符串的。

create table tb_test(shop varchar(10))
insert tb_test values('a')

alter PROCEDURE [dbo].sp_TEST
@strShopID varchar(1000)=''
AS
BEGIN
SET NOCOUNT ON;
declare @tbShop table(shopid varchar(32))
--declare @tbTopShop table(shopid varchar(32),Num int)
set @strShopID=@strShopID+','
while(len(@strShopID)>1)
begin
if left(@strShopID,1)=','
set @strShopID=substring(@strShopID,2,len(@strShopID))
insert @tbShop
select substring(@strShopID,1,charindex( ',',@strShopID)-1)
set @strShopID=substring(@strShopID,charindex( ',',@strShopID),len(@strShopID))

end
insert tb_test
select * from @tbshop where shopid not in(select * from tb_test)
END
sp_TEST 'a,b,c,d,e,f'
select * from tb_test

博客:http://www.haoyuncn.net/sql-split-insert

转载于:https://www.cnblogs.com/cyun/p/4243399.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值