创建动态 sql 查询

Creating a dynamic sql query(创建动态 sql 查询)
本文介绍了创建动态 sql 查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请查看此 SQL 代码:

Please see this SQL code:

DECLARE @MyQuery nvarchar(max)
set @MyQuery = 'SELECT TOP 1 @TranslatedMessageOutput = 
               ' + @LanguageName + ' FROM local_translation WHERE English =
               '+CHAR(39)+CHAR(39)+Convert(nvarchar(50),
               (select English from inserted))
                +CHAR(39)+CHAR(39)+CHAR(39)+
               ' AND [' + @LanguageDateName + '] NOT LIKE ''%1900%'''

如果我为英语输入 abc 这个查询就可以正常工作了.

If I type abc for English this query works just fine.

但是如果我输入 'abc' 为英语查询会抛出一个错误:

But if I type 'abc' for English the query is throwing an error:

字符串"后的非封闭引号.."附近的语法不正确

Unclosed quotation mark after the character string "". Incorrect syntax near "."

我该如何解决这个问题?

How do I solve this?

推荐答案

我怀疑您需要转义此查询的输出:

I suspect you will need to escape the output of this query:

(select English from inserted)

如在

(select replace(English, '''', '''''') from inserted)

在将结果连接到您的动态 SQL 语句之前,上述内容将用 '' 替换 '.但是对于任何动态 SQL,我强烈建议您使用绑定值来防止此类 SQL 语法错误和 SQL 注入!IE.你应该能够写出这样的东西:

The above will replace ' by '' before concatenating the outcome to your dynamic SQL statement. But with any dynamic SQL, I strongly suggest you make use of bind values to prevent such SQL syntax errors and SQL injection! I.e. you should be able to write something like this:

declare @English;
select @English = English from inserted;
set @MyQuery = 'SELECT TOP 1 @TranslatedMessageOutput = 
               ' + @LanguageName + 
               ' FROM local_translation WHERE English = @English'
               ' AND [' + @LanguageDateName + '] NOT LIKE ''%1900%''';
-- ...

这篇关于创建动态 sql 查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
SSIS: Model design issue causing duplications - can two fact tables be connected?(SSIS:模型设计问题导致重复-两个事实表可以连接吗?)
SQL Server Graph Database - shortest path using multiple edge types(SQL Server图形数据库-使用多种边类型的最短路径)
Invalid column name when using EF Core filtered includes(使用EF核心过滤包括时无效的列名)
How should make faster SQL Server filtering procedure with many parameters(如何让多参数的SQL Server过滤程序更快)
How can I generate an entity–relationship (ER) diagram of a database using Microsoft SQL Server Management Studio?(如何使用Microsoft SQL Server Management Studio生成数据库的实体关系(ER)图?)