如何在sql server中将字符串转换为查询

发布于 2024-12-12 04:16:19 字数 433 浏览 0 评论 0原文

如何添加包含 And 子句的字符串。但是当我们应用查询该字符串时,该字符串将被视为查询并满足所有和条件
我有一个查询,例如:-

Declare @WhereQuery varchar(max)

SET @WhereQuery='class=''BCA'' and RollNo=10 AND ID IN (SELECT ID FROM StudentMaster WHERE MARKS > 50)'

SELECT  * into #TempTable1
from StudentMaster 
where @WhereQuery

我也不想使用execute 或exec 函数来运行此查询。 我将添加上面提到的查询字符串,但这将无法正常工作。 我在 where 子句之后添加的变量被视为字符串,但我希望该字符串被视为查询。请帮忙。我也不想使用execute 或exec 函数来运行此查询。

How to add string in which we have And clause. but when we apply that string which query this string will be treated as Query and fulfill all and conditions
I have a query like:-

Declare @WhereQuery varchar(max)

SET @WhereQuery='class=''BCA'' and RollNo=10 AND ID IN (SELECT ID FROM StudentMaster WHERE MARKS > 50)'

SELECT  * into #TempTable1
from StudentMaster 
where @WhereQuery

I also don't want to use execute or exec function to run this query.
I am going to add string with query mention as above but this will not work properly.
The variable which I have added after where clause is treated as string but I want this string is treated as Query. Please help. I also don't want to use execute or exec function to run this query.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

偷得浮生 2024-12-19 04:16:19

下面的方法效果很好。但要格外小心,因为如果用户提供输入,它很容易受到 SQL 注入的影响。

create table #TempTable1 (.....)

Declare @selectQuery varchar(max)
set @selectQuery = 'SELECT * into #TempTable1 from StudentMaster '

Declare @WhereQuery varchar(max)

SET @WhereQuery='where class=''BCA'' and RollNo=10 AND ID IN (SELECT ID FROM StudentMaster WHERE MARKS > 50)'

exec (@selectQuery + @WhereQuery)

The below approach works fine. but be extra careful as it is susceptible to sql injection if user provides the input.

create table #TempTable1 (.....)

Declare @selectQuery varchar(max)
set @selectQuery = 'SELECT * into #TempTable1 from StudentMaster '

Declare @WhereQuery varchar(max)

SET @WhereQuery='where class=''BCA'' and RollNo=10 AND ID IN (SELECT ID FROM StudentMaster WHERE MARKS > 50)'

exec (@selectQuery + @WhereQuery)
嘴硬脾气大 2024-12-19 04:16:19

如果出现以下情况,您必须使用 EXEC 或 sp_exeutesql想要运行动态SQL。

如果您不想使用 EXEC,则编写非动态查询:

SELECT  * into #TempTable1
from StudentMaster 
where class='BCA' and RollNo=10 AND ID IN (SELECT ID FROM StudentMaster WHERE MARKS > 50)

You have to use EXEC or sp_exeutesql if you want to run dynamic SQL.

If you don't want to use EXEC then write non-dynamic queries:

SELECT  * into #TempTable1
from StudentMaster 
where class='BCA' and RollNo=10 AND ID IN (SELECT ID FROM StudentMaster WHERE MARKS > 50)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文