1、Split SQL Server 2008 新语法:
DECLARE @str VARCHAR(MAX)
SET @str = REPLACE(@teeIDs, ',', '''),(''')
SET @str = 'SELECT * FROM (VALUES(''' + @str + ''')) AS V(A)'
EXEC (@str)
据说这个SQL语法是SQL Server 2008的。
SELECT * FROM (VALUES(1),(2),(3)) AS V(A)
配合个临时表,用起来还算方便。
INSERT INTO #TMP
EXEC (@sql)
2、Split 兼容老的SQL Server的语法(推荐):
DECLARE @s VARCHAR(100) ,
@sql VARCHAR(1000)
SET @s = '1,2,3,4,5,6,7,8,9,10'
SET @sql = 'select col=''' + REPLACE(@s, ',', ''' union select ''')
+ ''''
PRINT @sql
EXEC (@sql)
-- CORE SQL:
--EXEC ( 'select col=''' + REPLACE(@s, ',', ''' union select ''') )
3、Join FOR XML PATH('') 观察下面三个SQL的查询结果的变化即可
SELECT UserName='admin' UNION SELECT 'test' UNION SELECT 'abc'
SELECT ',' + UserName FROM ( SELECT UserName='admin' UNION SELECT 'test' UNION SELECT 'abc') A FOR XML PATH('')
SELECT stuff( (SELECT ',' + UserName FROM ( SELECT UserName='admin' UNION SELECT 'test' UNION SELECT 'abc') A FOR XML PATH(''))
,1,1,'')