SQL Server 字符串拼接与拆分 string varchar Split and Join

时间:2022-05-11 07:32:05
1、Split    SQL Server 2008 新语法:
  1. DECLARE @str VARCHAR(MAX)
  2. SET @str = REPLACE(@teeIDs, ',', '''),(''')
  3. SET @str = 'SELECT * FROM (VALUES(''' + @str + ''')) AS V(A)'
  4. EXEC (@str)

据说这个SQL语法是SQL Server 2008的。
  1. SELECT * FROM (VALUES(1),(2),(3)) AS V(A)

配合个临时表,用起来还算方便。

  1. INSERT INTO #TMP
  2. EXEC (@sql)

2、Split    兼容老的SQL Server的语法(推荐):
  1. DECLARE @s VARCHAR(100) ,
  2. @sql VARCHAR(1000)
  3. SET @s = '1,2,3,4,5,6,7,8,9,10'
  4. SET @sql = 'select col=''' + REPLACE(@s, ',', ''' union select ''')
  5. + ''''
  6. PRINT @sql
  7. EXEC (@sql)
  8. -- CORE SQL:
  9. --EXEC ( 'select col=''' + REPLACE(@s, ',', ''' union select ''') )

3、Join  FOR XML PATH('')  观察下面三个SQL的查询结果的变化即可
 
  1. SELECT UserName='admin' UNION SELECT 'test' UNION SELECT 'abc'
  2. SELECT ',' + UserName FROM ( SELECT UserName='admin' UNION SELECT 'test' UNION SELECT 'abc') A FOR XML PATH('')
  3. SELECT stuff( (SELECT ',' + UserName FROM ( SELECT UserName='admin' UNION SELECT 'test' UNION SELECT 'abc') A FOR XML PATH(''))
  4. ,1,1,'')
SQL Server 字符串拼接与拆分 string varchar Split and Join