1

On tsql, I want to use variable as part of tsql code according to some conditions, is there a way to do the following:

DECLARE @mode BINARY = 0
DECLARE @stringCode VARCHAR(100)
.
.
.
if(@mode = 1)(
    @stringCode VARCHAR(100) = 'charindex(",", rtrim(col1_name), col2_name)'
)ELSE(
    @stringCode VARCHAR(100) = '1=1'
)

SELECT col1_name, col2_name, col3_name
    FROM table1_name AS T1
    INNER JOIN table2_name AS T2
    ON @stringCode 

The last query using the variable @stringCode as part of the code.

Well, it did not work like that, so I wanted to know if I could possibly apply this?

Please note that this code is just a test to demonstrate what I want to do

3
  • 1
    If you want to do this, then you need to learn about dynamic SQL. If you are attempting this and don't know what dynamic SQL is, you may need to learn about SQL in general. Commented Dec 8, 2016 at 15:26
  • msdn.microsoft.com/en-us/library/ms188001.aspx Commented Dec 8, 2016 at 15:29
  • Thanks for the note, I will read about dynamic SQL. I am glad that it is possible though Commented Dec 8, 2016 at 15:40

2 Answers 2

1

All you need is 'sp_executesql' system stored proc. It takes a string containing the query as input:

DECLARE @query nvarchar(4000)
SET @query = N'SELECT col1_name, col2_name, col3_name
    FROM table1_name AS T1
    INNER JOIN table2_name AS T2
    ON ' + @stringCode

EXEC sp_executesql @query
Sign up to request clarification or add additional context in comments.

Comments

0

I guess you could try something like this, but not sure if those are right join conditions.

if(@mode = 1)(
    SELECT col1_name, col2_name, col3_name
    FROM table1_name AS T1
    INNER JOIN table2_name AS T2
       ON charindex(",", rtrim(col1_name), col2_name)
)ELSE(
    SELECT col1_name, col2_name, col3_name
    FROM table1_name AS T1
    INNER JOIN table2_name AS T2
       ON 1=1
)

4 Comments

Thanks Juan, this what I am using now, but the reason I need to use a variable because there are more conditions and I also want to apply the same concepts in different ways. Your suggestion is good but not using what I am looking for
Then you need go for the dynamic SQL. as suggested in comments ;) , But again, you should double check those JOIN conditions, looks very weird
Yes, sorry I wrote the conditions just to demonstrate the code and they do look weird :)
Thanks @Juan Carlos Oropeza

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.