SQL QUOTENAME 添加单引号和逗号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22810003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 01:32:26  来源:igfitidea点击:

SQL QUOTENAME adding single quotes and a comma

sqlfunctionquotescomma

提问by Matt

I have a basic table which outputs.

我有一个输出的基本表。

field1
  a
  b
  c

Then i want to add single quotes and a comma so currently i have a simple QUOTENAME.

然后我想添加单引号和逗号,所以目前我有一个简单的 QUOTENAME。

QUOTENAME(field1,'''')

Which outputs the following results.

输出以下结果。

field1
  'a'
  'b'
  'c'

But i cant figure out how to get the QUOTENAME to output results like this.

但我不知道如何让 QUOTENAME 输出这样的结果。

field1
  'a',
  'b',
  'c',

回答by TechDo

Try:

尝试:

QUOTENAME(field1,'''')+','

回答by SQLnbe

I know you got your answer but just wanted to make an addition if someone else looks at this and is wondering how to get rid of the last comma after the last value in case they are using the resultset for a dynamic query.

我知道你得到了你的答案,但只是想补充一下,如果其他人看到这个并且想知道如何去掉最后一个值之后的最后一个逗号,以防他们使用结果集进行动态查询。

Declare @MyString nvarchar(max)
select @MyString += QuoteName (field1.'''') + ','
from YourTable Name

Set @MyString = left (@MyString, Len ( @MyString) - 1 )

And to view the results a

并查看结果

Print @MyString 

can be added to evaluate the results.

可以添加来评估结果。

Hope this helps others looking for this logic when using the quotename and needing that last comma removed :-)

希望这可以帮助其他人在使用引用名称并需要删除最后一个逗号时寻找此逻辑:-)

回答by PMargarido

that doesnt work you dont initialize @MyString so concatenating anything with null will be null

这不起作用你不初始化@MyString 所以用null连接任何东西都会是null

but using this aproach you dont need to initialize it

但是使用这种方法你不需要初始化它

DECLARE @MyString NVARCHAR(MAX)
SELECT  @MyString = COALESCE(@MyString+ ',', '') + QUOTENAME(field1, '''') 
FROM    YourTable Name