简体   繁体   English

如何在存储过程SQL Server中的BCP SQL查询中转义双引号

[英]How to escape double quotes in bcp sql query in stored procedure sql server

The following is my stored procedure code: 以下是我的存储过程代码:

Alter PROCEDURE [dbo].[ConvertToFile]

    @TempFileName varchar(8000)
AS
BEGIN
    SET NOCOUNT OFF;

    DECLARE @bcpFileCmd varchar(8000)


SET @bcpFileCmd= 'bcp "SELECT id,full_Name,message from NotesTable " queryout '+@TempFileName+' -t, -c -T'

    EXEC master..xp_cmdshell @bcpFileCmd

END

BCP dumps all the data from NotesTable in file. BCP从文件中的NotesTable转储所有数据。 But I need to enclose the message results with double quotes. 但是我需要用双引号将消息结果引起来。 The datatype for message field is text. 消息字段的数据类型是文本。 I'm not able to append it in select query in BCP. 我无法将其附加到BCP的选择查询中。

You will need to concatenate double quotes to the beginning and end of your message results, and escape both the single quotes and double quotes: 您需要将双引号连接到消息结果的开头和结尾,并转义单引号和双引号:

SET @bcpFileCmd= 'bcp "SELECT id, full_Name, ''""'' + message + ''""'' from NotesTable " queryout '+@TempFileName+' -t, -c -T'

If you need to retain the column name, you should also alias it like so (might not be necessary if you're just outputting to a file): 如果您需要保留列名,则还应该像这样对它起别名(如果只是输出到文件,则可能不需要):

SET @bcpFileCmd= 'bcp "SELECT id, full_Name, ''""'' + message + ''""'' ''message'' from NotesTable " queryout '+@TempFileName+' -t, -c -T'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM