Sqlserver表值函数来获取逗号分隔的ID
其功能为: 将字符串如'1,2,3,4,5,6' 拼接成SQL里面的id
1:使用:
select * from Student where id IN( SELECT * FROM dbo.F_SPLIT('1,2,3,4',',') )
2:定义表值函数:
USE [CRM_CN2] GO /****** Object: UserDefinedFunction [dbo].[F_SPLIT] ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ============================================= Author: zrf Create date: 2019 09 10 Description: 将表中字段pid:里面的值 如:"12,33,15,36,889" -->转换成一张表 ============================================= ALTER FUNCTION [dbo].[F_SPLIT] ( @SourceSql nvarchar(4000), @StrSeprate varchar(10) ) RETURNS @temp TABLE(Temp_Field nvarchar(2000)) AS BEGIN declare @i int set @SourceSql = rtrim(ltrim(@SourceSql)) set @i = charindex(@StrSeprate, @SourceSql) while @i >= 1 begin insert @temp values(left(@SourceSql, @i - 1)) set @SourceSql = substring(@SourceSql, @i + 1, len(@SourceSql) - @i) set @i = charindex(@StrSeprate, @SourceSql) end if @SourceSql <> '\' insert @temp values(@SourceSql) RETURN END
如有疑问或者错误的地方,请跟帖,本人会第一时间答复以及相互学习,谢谢!个人会不断的上传自己的学习心得!
好了今天就先到这里,下次有时间再更新,如果存在不合理的地方,欢迎大家多多指教留言!!!