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


    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,'')





  • 相关阅读:
    是否有人会想起
    春风下也有落叶
    to kongove:呵呵~是啊,偶尔吹得玩下,仅当娱乐而已……
    木头人の狂想
    夜行静思湖
    [学习标准库]math.h
    [学习标准库]ctype.h
    [学习标准库]stdio.h
    句子
    [学习标准库]assert.h
  • 原文地址:https://www.cnblogs.com/ybst/p/5129078.html
Copyright © 2020-2023  润新知