Reputation: 15
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 :)
Upvotes: 0
Views: 370
Reputation: 40359
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, '
.
Upvotes: 0
Reputation: 27324
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.
Upvotes: 2