简体   繁体   English

如何在T-SQL SELECT语句的输出上将单引号切换为双单引号

[英]How do I Switch single quotes to double single quotes on output from T-SQL SELECT statement

I am trying to script the creation of the INSERT SQL for data in a table. 我正在尝试对表中数据的INSERT SQL创建脚本。 (similar to the SQL Server built in scripts) (类似于内置于脚本中的SQL Server)

DECLARE @HEADER varchar(255)

SET @HEADER = 'insert into Table ( Column1 , Column2)
values ( N'''

SELECT 
@Header + Column1 + ''', N''' + Column2 + ''')'
+ CHAR(10)
FROM Table
ORDER BY Column1

In Column1 I have text that contains single quotes and I need it to come out as double single quoted text like it does when using "Generate scripts" directly from SQL Server. 在Column1中,我有包含单引号的文本,我需要它像使用直接从SQL Server直接使用“生成脚本”时一样,以双引号引起来。

Use the REPLACE function to double up your quotes, and you'll need to wrap the resulting string in quotes. 使用REPLACE函数将双引号加倍,然后需要将结果字符串包装在双引号中。 Note that this works for NOT NULL columns, so tweak it if you need to support nullable columns. 请注意,这适用于NOT NULL列,因此,如果需要支持可为NOT NULL列,请对其进行调整。

SELECT
  'INSERT INTO Table (Column1, Column2) VALUES (N''' +
     REPLACE(Column1, '''', '''''') + ''', N''' +
     REPLACE(Column2, '''', '''''') + ''')'
FROM Table
ORDER BY Column1

You can use the QUOTENAME function. 您可以使用QUOTENAME函数。

SELECT 
@Header + QUOTENAME(Column1) + ''', N''' + Column2 + ''')'
+ CHAR(10)
FROM Table
ORDER BY Column1

I am guessing you want to generate an insert script based on an existing table? 我猜您想基于现有表生成插入脚本吗?

I would recommend you download SSMS Tools . 我建议您下载SSMS工具 It's a great add in with additional features for use with SSMS. 这是与SSMS一起使用的附加功能的绝佳添加。 One of these features allows you to right click a table and it will generate an insert script for you that contains the data within the table. 这些功能之一允许您右键单击一个表,它将为您生成一个插入脚本,其中包含表中的数据。

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

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