How can I use a parameter instead of a field name like:
Declare @Thecode varchar(10)
Set @Thecode= ‘code’ --'code' is field name.
Select @Thecode from sqltable
How can I use a parameter instead of a field name like:
Declare @Thecode varchar(10)
Set @Thecode= ‘code’ --'code' is field name.
Select @Thecode from sqltable
Here is the correction in your query:
SET @Thecode= ‘code’ --'code' is field name.
SET @query='Select '+@Thecode+' from sqltable'
EXECUTE(@query)
There are two ways to execute dynamic SQL in SQL Server: use the sp_executesql
system stored procedure or the EXECUTE()
operator.
And for more details about the dynamic SQL execution Follow the below link:
https://www.mssqltips.com/sqlservertip/1160/execute-dynamic-sql-commands-in-sql-server/
I think you are looking for the Dynamic SQL.
If it is so then please check the following solution:
Note: Tested in SQL Server 2008 R2
Declare @Thecode varchar(10)
DECLARE @query VARCHAR(MAX)
Set @Thecode= 'code' --'code' is field name.
SET @query = 'SELECT '+ @Thecode +' from sqltable';
EXEC(@query)
Always mention the DBMS in the tags while posting the question. And take care of SQL Injection
For more details about Dynamic SQL.