declare @sum as nvarchar(20) = 'sum(Salary)'
select @sum from Employee
I want to do something like this. I need to store my sql query part in variable and use that variable in sql query. Is it possible in any way?
declare @sum as nvarchar(20) = 'sum(Salary)'
select @sum from Employee
I want to do something like this. I need to store my sql query part in variable and use that variable in sql query. Is it possible in any way?
SQL Server does not support macro-substition. It does however allow for DYNAMIC SQL. Below is a simple example
declare @sum as nvarchar(20) = 'sum(Salary)'
Declare @SQL varchar(max) = 'select '+@Sum+' from Employee'
Exec(@SQL)
Now, to be clear, there are risks of SQL Injection. Take a peek at http://bobby-tables.com/
YOU CAN USE DYNAMIC QUERY
BEGIN TRAN
DECLARE @sum NVARCHAR(20) = 'sum(Salary)',@SQL VARCHAR(4000)
SET @SQL=''
SET @SQL = @SQL + 'SELECT '+@Sum+' FROM Employee'
PRINT @SQL
EXEC(@SQL)
ROLLBACK TRAN
id 'sum(salary)' is like that then it should return a result of
declare @sum as nvarchar(20) = 'sum(Salary)'
result a literal string
sum(Salary)
but if like:
declare @sum as nvarchar(20)
select @sum = sum(Salary),column1,..and so on from your table
then it should return a result from your function