简体   繁体   中英

Invalid column name 'Columnname' in SQL Server

alter procedure NewUserTableCreation(@Username varchar(50))
as
    declare @CreateUserTable NVARCHAR(MAX)
    declare @AddRecord NVARCHAR(MAX)
    declare @VisitedClothesKids varchar(50)='VisitedClothesKids'
    declare @InitialCount varchar(20)='0'
BEGIN
    --Building query for creating a user table
    SET @CreateUserTable = 'create table ' + @Username +
                           '_Table(UserActivityData varchar(50),DataValue varchar(20))'
    EXEC(@CreateUserTable);

    --Adding Records in the user table
    SET @AddRecord = 'insert into ' + @Username + '_Table(UserActivityData, DataValue)
                      values(' + @VisitedClothesKids + ','  + @InitialCount + ')'
    EXEC(@AddRecord);
END
GO

I'm executing this procedure from C# code. A table is successfully created and then an exception is thrown saying,

Invalid column name 'VisitedClothesKids'
Invalid column name 'InitialCount'

Please help! Many Thanks :)

The issue is that the string being concatenated itself is not putting the values in quotes:

values('+@VisitedClothesKids+','+@InitialCount+')'

becomes

values(VisitedClothesKids,0)'

when you want it to be

values('VisitedClothesKids','0')'

We should also warn you that the technique you are using here is open to SQL Injection and should be avoided.

To solve this kind of problem, you have to review the statement that your are executing. For example, if you did this (passing in "MyData" for a table name):

PRINT @AddRecord;
EXEC(@AddRecord);

You would see the following as output:

insert into MyData_Table(UserActivityData,DataValue) values(VisitedClothesKids,0)'

Which fails because SQL doesn't know what "VisitedClothesKids" is. You want the statement to be

insert into MyData_Table(UserActivityData,DataValue) values('VisitedClothesKids',0)'

with the quotes to designate the literal string. To get this, modify your "build statement like so:

SET @AddRecord = 'insert into '+@Username+'_Table(UserActivityData,DataValue)
values('''+@VisitedClothesKids+''','+@InitialCount+')'

In this context, SQL will interpret (or "escape") the two single-quotes, '' as a single quote, ' .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM