博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
mssql字符串分割后的值,把表中不存在的插入表中
阅读量:6872 次
发布时间:2019-06-26

本文共 1732 字,大约阅读时间需要 5 分钟。

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

使用场景,自行思考……

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

--实现分割的函数

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

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

create table tb_test(shop varchar(10))insert tb_test values('a')alter PROCEDURE [dbo].sp_TEST@strShopID varchar(1000)=''ASBEGINSET NOCOUNT ON;declare @tbShop table(shopid varchar(32))--declare @tbTopShop table(shopid varchar(32),Num int)set @strShopID=@strShopID+','while(len(@strShopID)>1)beginif left(@strShopID,1)=','set @strShopID=substring(@strShopID,2,len(@strShopID))insert @tbShopselect substring(@strShopID,1,charindex( ',',@strShopID)-1)set @strShopID=substring(@strShopID,charindex( ',',@strShopID),len(@strShopID))endinsert tb_testselect * from @tbshop where shopid not in(select * from tb_test)ENDsp_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

你可能感兴趣的文章
sass进阶篇
查看>>
为项目配置logback日志
查看>>
另外一种C#多选下拉框
查看>>
javascript中base64和Gzip的使用
查看>>
《大话西游》/月光宝盒/大圣取亲
查看>>
laravel创建资源路由控制器
查看>>
使用 Go 的 struct tag 来解析版本号字符串
查看>>
Objective-c——UI基础开发第十一天(UICollectionView)
查看>>
CentOS 7 搭建Jenkins+JDK+Git+Maven+Gradle持续集成系统
查看>>
yarn的 文件名、目录名或卷标语法不正确
查看>>
《C专家编程》笔记(四)——数组和指针并不相同
查看>>
最新工作环境整理遇到的一些问题。
查看>>
ip通信基础第七周(下)
查看>>
mysql5.6.38占用内存过大问题解决
查看>>
那些年学过的计算机编程语言
查看>>
MySQL----外键
查看>>
全面总结: Golang 调用 C/C++,例子式教程
查看>>
安卓手机的屏幕规格很多。app开发者在设计User Interface的时候,要怎么处理,才能适应不同屏幕大小?...
查看>>
php合并数组并保留键值的方法
查看>>
WinEdit编辑器中中文乱码
查看>>