您好,欢迎访问一九零五行业门户网

在论坛中出现的比较难的sql问题:17(字符分拆2)

最近,在论坛中,遇到了不少比较难的sql问题,虽然自己都能解决,但发现过几天后,就记不起来了,也忘记解决的方法了。 所以,觉得有必要记录下来,这样以后再次碰到这类问题,也能从中获取解答的思路。 1、存储过程 表a: aid bid status 1 1 0 1 2 0 2 1 0
最近,在论坛中,遇到了不少比较难的sql问题,虽然自己都能解决,但发现过几天后,就记不起来了,也忘记解决的方法了。
所以,觉得有必要记录下来,这样以后再次碰到这类问题,也能从中获取解答的思路。
1、存储过程
表a:
aid bid status
1 1 0
1 2 0
2 1 0
1 111 0
11 11 0
每条数据aid 联合bid 是唯一的,如何写存储过程进行批量操作。
传入[{aid:1,bid:2},{aid:11,bid:11}]
查询出下表数据:
aid bid status
1 2 0
11 11 0
建表语句:
create table a(aid int, bid int, statuss int )insert a select 1,1,0 union allselect 1,2,0 union all select 2,1,0 union allselect 1,111,0 union allselect 11,11,0go
--1.字符串分拆函数if exists(select * from sys.objects where name = 'f_splitstr' and type = 'tf') drop function dbo.f_splitstrgocreate function dbo.f_splitstr( @s varchar(8000), --要分拆的字符串 @split varchar(10) --分隔字符) returns @re table( --要返回的临时表 col varchar(1000) --临时表中的列 )asbegin declare @len int set @len = len(@split) --分隔符不一定就是一个字符,可能是2个字符 while charindex(@split,@s) >0 begin insert into @re values(left(@s,charindex(@split,@s) - 1)) set @s = stuff(@s,1,charindex(@split,@s) - 1 + @len ,'') --覆盖:字符串以及分隔符 end insert into @re values(@s) return --返回临时表endgo create proc dbo.pro_a@param varchar(100)as declare @str varchar(100)declare @sql nvarchar(4000)set @str = ''set @sql = ''if object_id('tempdb..#temp') is not null drop table #temp--把拆分后的字段,插入到临时表select left(col,charindex(',',col)-1) as aid, substring(col,charindex(',',col)+1,len(col)) as bid into #tempfrom dbo.f_splitstr(@param,';') t--生成动态语句set @sql = 'select * from a where exists(select 1 from #temp where #temp.aid = a.aid and #temp.bid = a.bid)'exec(@sql)goexec pro_a '1,2;11,11'/*aid bid statuss1 2 011 11 0*/
另一种方法:if object_id('dbo.pro_a') is not null drop proc pro_agocreate proc dbo.pro_a@param varchar(100)as declare @str varchar(100)declare @sql nvarchar(4000)set @str = @paramset @sql = ''set @str = replace(replace(replace(replace(replace(@str,'[',''),']',''),'},{',';'), '{',''),'}','') set @str = 'select '+replace(replace(@str,';',' union select '),':','=')if object_id('tempdb..#temp') is not null drop table #tempcreate table #temp(aid int, bid int)--把数据插入到临时表中insert into #temp(aid,bid)exec(@str)--生成动态语句set @sql = 'select * from a where exists(select 1 from #temp where #temp.aid = a.aid and #temp.bid = a.bid)'exec(@sql)--print @strgoexec pro_a '[{aid:1,bid:2},{aid:11,bid:11}]'/*aid bid statuss1 2 011 11 0*/
其它类似信息

推荐信息