Click here to Skip to main content
15,921,210 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
hello,

i have a table

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

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


It is possibile create a dynamic if?

example

SQL
DECLARE @myvar
SET @myvar ='070'


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


SQL
IF @myvar + @operation + @Value


thank you in advance

What I have tried:

i have tried to concatenate my variable but i fear tha is not possibile
Posted
Updated 2-Aug-16 12:04pm
Comments
[no name] 2-Aug-16 7:29am    
Could you send full condition formate?
Tomas Takac 2-Aug-16 8:13am    
It is possible build and run SQL on the fly - depends on what you are trying to do. So post all your relevant code and explain where is the problem. But if it's your fear what is holding you back then this is not the right forum.
Member 10766684 2-Aug-16 9:34am    
this is my code

BEGIN


DECLARE db_cursor CURSOR FOR
SELECT Position, Lenght,Value, Operation
FROM dbo.RulesStringLabel
where Custom = '0'

OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @Position, @Lenght, @Value, @Operation

WHILE @@FETCH_STATUS = 0
BEGIN

SELECT @ValueCheck = SUBSTRING (@Label, @Position, @Lenght)
SELECT @OperationString = @Operation +' '+@Value

IF @ValueCheck + @OperationString




FETCH NEXT FROM db_cursor INTO @Position, @Lenght, @Value, @Operation
END

CLOSE db_cursor
DEALLOCATE db_cursor




END
Member 10766684 2-Aug-16 9:36am    
My problem is on if statement, i cant translate the operator...

1 solution

See the small example below.

SQL
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


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.
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900