添加'到字符串sql

时间:2015-03-03 13:41:04

标签: sql sql-server string

我得到了这段代码,结果是:

9316C747-76F7-4F3C-B35F-8E4CC96E214D,
232009BF-9867-4A5C-BD83-E41F1398ECA8,
68C15098-521F-4BE8-817B-26E73662E4EC,
F1F38030-632B-4756-A3B7-C7702D3BAA08,
D13947E5-E1BB-42CD-A5F8-02A9C0830979,
6BA64EE9-8D64-4545-A8D6-3E8A1DD33877,
DBA27DB9-FDE3-432B-B713-6801A3D01CA2

我有兴趣让列表看起来像这样:

'D91A4FE8-663A-4DDF-B6DB-95145DAD270B',
'8B30CBCC-8093-42A5-A1C8-FE88DFB7640F',
'A5E3202D-804C-477E-B54F-B80E72E871D9',
'5CE13B9B-9D31-4A03-9C5C-19B1C6D5915F',
'DB3447BC-2A89-4D8C-A865-6EB424D0EDA0',
'E7C0AB31-DA72-4456-971D-95881EC6B7F7',
'DDDECF74-7192-4B5F-91D6-ADF8756FFBFF',
'AF3D30C3-7233-4146-9BA0-13FB03B3BF13'

怎么可能这样做?

DECLARE @listStr VARCHAR(MAX)
SELECT @listStr = COALESCE(@listStr+',' , '') + cast(int_guid as varchar(max)) 
FROM ex_in
SELECT @listStr

2 个答案:

答案 0 :(得分:0)

您需要添加额外的报价。试试这个。

DECLARE @listStr VARCHAR(MAX)
SELECT @listStr = COALESCE(@listStr+''',''' , '') + cast(int_guid as varchar(max)) 
FROM ex_in
SELECT '''' + @listStr+'''' 

示例演示

DECLARE @str VARCHAR(max)

SELECT @str = Isnull(@str+''',''', '') + a
FROM   (SELECT '9316C747-76F7-4F3C-B35F-8E4CC96E214D' a
        UNION
        SELECT '232009BF-9867-4A5C-BD83-E41F1398ECA8'
        UNION
        SELECT '68C15098-521F-4BE8-817B-26E73662E4EC')dd

PRINT '''' + @str + '''' 

答案 1 :(得分:0)

试试这个:

DECLARE @listStr VARCHAR(MAX) = ''

SELECT @listStr = @listStr + ',' + '''' + CAST(int_guid AS varchar(max)) + ''''
FROM ex_in

SET @listStr = STUFF(@listStr, 1, 1, '')

SQL Fiddle Demo here