带动态代码的IF语句 [英] IF statement with dynamic code

查看:99
本文介绍了带动态代码的IF语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,



i有一张桌子



..... |价值|操作|

_____ | _____ | _________ |



..... | 001 | > = |

..... | 009 | < = |





有可能创建一个动态if?



示例



hello,

i have a table

.....|Value|Operation|
_____|_____|_________|

.....| 001 | >= |
.....| 009 | <= |


It is possibile create a dynamic if?

example

DECLARE @myvar
SET @myvar ='070'


DECLARE @operation
DECLARE @Value
SELECT @operation = operation from mytable
SELECT @value = value from mytable







IF @myvar + @operation + @Value





提前谢谢



我的尝试:



i试图连接我的变量,但我担心不可能



thank you in advance

What I have tried:

i have tried to concatenate my variable but i fear tha is not possibile

推荐答案

请参阅下面的小例子。



See the small example below.

Declare @A nvarchar(100)
Declare @S nvarchar(100)
Declare @T nvarchar(10)

Select @T = '1 '
Select @A = ' = 2'
Select @S = 'if ' + @T +  @A + ' begin Select * from Table where SomeField = '''xx''' end'
Select @S --Display resultant SQL Statement only
EXECUTE sp_executeSQL @S





这背后的原理是创建一个字符串,它是您拥有的SQL语句,然后执行该SQL语句。 (希望if语句不会太长)



参见 sp_executesql(Transact-SQL) [ ^ ]



创建SQL语句时要小心单引号,因为这些需要根据需要添加。我也添加了一个例子。



例如选择陈述中的'A'最终将成为'''A'''。



参见如何包含sql查询中的单引号 [ ^ ]



你最终应该得到的是一个SQL语句,它是一个可以执行的大型nvarchar或字符串。



The principle behind this is to create a string which is your SQL statement out of the conditions you have and then execute that SQL statement. (hopefully the if statement is not too long)

See sp_executesql (Transact-SQL)[^]

When creating the SQL statement be careful of single quotes as these need to be added in as required. I have added an example of this as well.

e.g. 'A' in a select statement will end up being become '''A'''.

See How to include a single quote in a sql query[^]

What you should end up with is a SQL statement as a large nvarchar or string that can be executed.


这篇关于带动态代码的IF语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆