简体   繁体   English

SQL Server中的无效列名“ Columnname”

[英]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. 我正在从C#代码执行此过程。 A table is successfully created and then an exception is thrown saying, 成功创建一个表,然后引发异常,

Invalid column name 'VisitedClothesKids' 无效的列名“ VisitedClothesKids”
Invalid column name 'InitialCount' 无效的列名“ 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. 我们还应该警告您,此处使用的技术对SQL Injection是开放的,应避免使用。

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): 例如,如果您这样做(将“ MyData”作为表名传递):

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. 失败是因为SQL不知道什么是“ VisitedClothesKids”。 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: 为此,请按如下所示修改您的“ build语句:

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, ' . 在这种情况下,SQL会将两个单引号''解释(或“转义”)为单引号'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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