Question

I have this stored procedure that accept a comlumn name as inptu parameter. The SELECT statement will select a column according to input parameter

create procedure getColumn (@whichColumn varchar)
as
begin
    declare @sql nvarchar(max) 
    set @sql = 'SELECT [' + @whichColumn + ']' 
        + ' FROM myTable'
        + ' where ['+ @whichColumn + '] is not null'
        + ' and [' + @whichColumn + '] != '''' ' ;
    exec sp_executesql @sql
end

When I execute this stored procedure,

exec getColumn 'Apple';

the error says "Invalid column name 'A' " . I cannot see why it only gets the first character of the input

Was it helpful?

Solution 3

Change this line

create procedure getClumn (@whichColumn varchar)

to

create procedure getClumn (@whichColumn varchar(max))

because if you are not assign size of varchar at that time it consider only one character so it get only one character A and generate error.

OTHER TIPS

Check out your parameter declaration:

@whichColumn varchar

From MSDN:

When n is not specified in a data definition or variable declaration statement, the default length is 1.

So that's a single-letter varchar. Try to specify a size:

@whichColumn varchar(50)

Or even better, use the system-defined type for object names:

@whichColumn sysname
create procedure getColumn (@whichColumn nvarchar(128))   --<-- Maximum column name lenght
as
begin
    declare @sql nvarchar(max); 
    set @sql =   N'SELECT ' + QUOTENAME(@whichColumn)+ N' FROM myTable'
               + N' where '+ QUOTENAME(@whichColumn) + N' is not null'
               + N' and ' + QUOTENAME(@whichColumn)  +  N' != '''' ' ;
    exec sp_executesql @sql
end

On a side note Using square brackets in you concatinating string isnt the same as using QUOTENAME function.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top