简体   繁体   English

动态SQL的良好做法

[英]good practice with dynamic sql

I use tons of dynamic SQL - I figured that there must some good guidelines, frameworks and/or tools to help one use dynamic SQL queries. 我使用了大量的动态SQL-我认为必须有一些好的准则,框架和/或工具来帮助人们使用动态SQL查询。 I'm looking for any suggestions on how exactly should one compose dynamic SQL query (with out the obvious solution of simply writing it, then adding ' ' ect). 我正在寻找关于究竟应该如何构成动态SQL查询的任何建议(没有简单地编写它,然后添加''ect的明显解决方案)。

The big problem here that sometimes it gets way to messy (dynamic sql that contains another dynamic sql ect). 这里的最大问题是有时会变得混乱(包含另一个动态sql的动态sql)。

If it matters at all, I am using sql-server. 如果很重要,我正在使用sql-server。

I'll take any advice I can get, Thanks! 我会接受任何建议,谢谢! ;) ;)

Vague question.. But one piece of advice: 含糊的问题..但是一个建议:

Use sp_executesql and pass in any variables/parameters whenever possible to prevent SQL injection 使用sp_executesql并尽可能传递任何变量/参数以防止SQL注入

If possible generate the dynamic SQL as much as possible, don't write it yourself. 如果可能的话,尽可能多地生成动态SQL,请不要自己编写。

Execute the dynamic SQL without appending the parameters to the SQL string, use parameters and pass those to sp_executesql to avoid having to do double quoting (too tedious). 在不将参数附加到SQL字符串的情况下执行动态SQL,使用参数并将其传递给sp_executesql以避免必须进行双引号(过于繁琐)。 It is also a solid guard against SQL Injection. 它也是防止SQL注入的坚实防护。 Example: 例:

DECLARE @stmt NVARCHAR(MAX)='SELECT * FROM your_table WHERE id=@par1 AND ... AND thename=@parn;';
EXECUTE sp_executesql @stmt, N'@par1 INT, ..., @parn VARCHAR(256)', @par1, ... , @parn;

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

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