SQL Server 字符串拼接、讀取

1、查詢結果使用,字符串拼接html

declare @names nvarchar(1000)
declare @ParmDefinition nvarchar(1000)
declare @sqltext nvarchar(500)
set @sqltext=N'Select @names=isnull(@names + '','' , '''' ) + isnull(列名, '''' ) From 表名'
set @ParmDefinition = N'@names nvarchar(1000) OUTPUT';
exec sp_executesql
  @sqltext,
  @ParmDefinition,
  @names=@names OUTPUT
select @names as Res

2、SQL函數 獲取「,」字符串長度sql

Create function [dbo].[GetSplitLength]
(
  @String nvarchar(max), --要分割的字符串
  @Split nvarchar(10) --分隔符號
)
returns int
as
begin
  declare @location int
  declare @start int
  declare @length int
 
  set @String=ltrim(rtrim(@String))
  set @location=charindex(@split,@String)
  set @length=1
  while @location<>0
  begin
    set @start=@location+1
    set @location=charindex(@split,@String,@start)
    set @length=@length+1
  end
  return @length
end

3、SQL函數  遍歷「,」拼接的字符串函數

 

create function [dbo].[GetSplitOfIndex]
 (
  @String nvarchar(max), --要分割的字符串
  @split nvarchar(10), --分隔符號
  @index int --取第幾個元素
 )
 returns nvarchar(1024)
 as
 begin
  declare @location int
  declare @start int
  declare @next int
  declare @seed int
 
  set @String=ltrim(rtrim(@String))
  set @start=1
  set @next=1
  set @seed=len(@split)
 
  set @location=charindex(@split,@String)
  while @location<>0 and @index>@next
  begin
    set @start=@location+@seed
    set @location=charindex(@split,@String,@start)
    set @next=@next+1
  end
  if @location =0 select @location =len(@String)+1
 
  return substring(@String,@start,@location-@start)
 end

4、FOR XML PATH 使用 spa

SELECT 列名+',' FROM 表名 FOR XML PATH('')

https://www.cnblogs.com/doubleliang/archive/2011/07/06/2098775.htmlcode

5、IN 參數查詢htm

create   function   [dbo].[f_split](@c   varchar(2000),@split   varchar(2))   

returns   @t   table(col   varchar(20))   

as   

    begin     

      while(charindex(@split,@c)<>0)   

        begin   

          insert   @t(col)   values   (substring(@c,1,charindex(@split,@c)-1))   

          set   @c   =   stuff(@c,1,charindex(@split,@c),'')   

        end   

      insert   @t(col)   values   (@c)   

      return   

    end

這樣就能夠直接使用IN來查詢了 查詢語句以下:blog

select schoolname  from school_info where code in(select col from [dbo].[f_split](@area,','))字符串

相關文章
相關標籤/搜索