Ofir Hadad
Ofir Hadad

Reputation: 1900

How to use a value of cell as a SELECT param in SQL SERVER

I have two tables.

1.TextLang Table:

| Key | En | Uk |
|'000'| 00 | 01 |

2.Users Table

| Id | Language |
|'11'| 'En'     |

I want to create a query that get the Value from Users Table and use it as a select param to get a value from TextLang Table.

Example:

SELECT Value(Users.Language) FROM TextLang 
INNER JOIN Users ON Users.Id='11'
WHERE Key='000'

Result:

| En |
| 00 |

So I expect Value(Users.Language) to be equals to 'En' And To get in this select the value 00

How would I do this? Thanks!

Upvotes: 0

Views: 175

Answers (1)

Kahn
Kahn

Reputation: 1660

Something like this TSQL will work, but it's not pretty. Something that's relatively fast to come up with though.

Either way, as far as I know, you're going to have to build some kind of dynamic SQL to be able to do what you're trying to do. :)

DECLARE @SQL VARCHAR(MAX), @LAN_COLUMN VARCHAR(25)

SELECT @LAN_COLUMN = Language
FROM TextLang
JOIN Users ON Users.Id='11'
WHERE Key = '000'

SELECT @SQL = 
'Select '+@LAN_COLUMN+' FROM TextLang '
+' JOIN Users ON Users.Id=''11'''
+' WHERE Key = ''000'''

EXEC(@SQL)

Upvotes: 1

Related Questions