嗨,我正在使用 SQLServer2008。
在我的表格中有一个字段“代码”。
当我写查询时
select Code from Table1
然后它给出以下输出
Code
----
9
8
7
6
5
10
31
我需要的输出是:
["9","8","7","6","5","10","31"]
我的表中有大约 14000 个代码。 我怎样才能得到这个结果?谢谢。
试试这个 -
DECLARE @temp TABLE(Code INT)
INSERT INTO @temp (Code)
VALUES (9),(8),(7),(6),(5),(10),(31)
SELECT STUFF((
SELECT ', "' + CAST(Code AS VARCHAR(10)) + '"'
FROM @temp
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '[') + ']'
输出:
["9", "8", "7", "6", "5", "10", "31"]
这是您的询问:
DECLARE @var varchar(8000)
SET @var = '['
SELECT @var = @var + '"' + convert(varchar(100),Code) + '",' FROM Table1
SET @var = SUBSTRING(@var,0,LEN(@var)) + ']'
SELECT @var
SUBSTRING(@var,0,LEN(@var))
删除字符串末尾不必要的逗号
try this
DECLARE @Str VARCHAR(MAX)
SELECT @Str = COALESCE(@Str + ',', '') + '"'+CAST(Code AS VARCHAR(50))+'"'
FROM Table1
SELECT '['+@Str+']'
试试这个
declare @formattdstring varchar(100)
set @formattdstring=''
select @formattdstring=@formattdstring+'"'+ Code +'",' from Table1
select '['+@formattdstring+']' as formattedstring
干杯!!!
DECLARE @ClntIDs VARCHAR(MAX) = 'Alice,Bob,Carol , Dan,Erin,Frank,Eve';
SELECT value FROM STRING_SPLIT(@ClntIDs, ',');
DECLARE @Quoted VARCHAR(MAX) = '';
SELECT @Quoted = CONCAT (@Quoted, '''', TRIM (value), ''', ') FROM STRING_SPLIT(@ClntIDs, ',');
-- To remove the last comma
SET @Quoted = LEFT(@Quoted, LEN (@Quoted) - 1);
SELECT @Quoted;