Put a variable as a title in an sql server query

3

I want you to show me a variable variable in the header.

When I do this:

declare @dato char(6)
declare @sql varchar(800)
set @dato='201601'
select @sql='select @dato as '+ @dato
exec(@sql)

I get this error:

  

Msg 137, Level 15, State 2, Line 1 Must declare the scalar variable "@dato".

And I want it to appear like this:

    
asked by Oscar C 14.09.2016 в 17:52
source

2 answers

5

You need to add the single quotes so that @dato is understood as a string:

declare @dato char(6)
declare @sql varchar(800)
set @dato = '201601';

select @sql='select ''' + @dato + ''' as ' + QUOTENAME(@dato);
exec(@sql);

Another way is that you use sp_executesql , which allows you to pass parameters:

declare @dato char(6)
declare @sql nvarchar(800)
set @dato = '201601'

select @sql = N'select @dato as ' + QUOTENAME(@dato);

EXEC SP_EXECUTESQL @sql, N'@dato char(6)', @dato = @dato;
    
answered by 14.09.2016 / 17:56
source
0

Place a semicolon after the char (6)

declare @dato char(6);
declare @sql varchar(800);
set @dato='201601';
select @sql='select @dato as '+ @dato;
exec(@sql);
    
answered by 14.09.2016 в 17:56