1

I want to insert into Tables but error:

Msg 207, Level 16, State 1, Line 1 Invalid column name 'A'. Msg 207, Level 16, State 1, Line 1 Invalid column name 'B'.

My table names is : TBL_PriceKeyBoard Keyboard is variable and maybe hard or ram but TBL_Price is static.

Declare @sql as nvarchar(max)
Declare @TBL as nvarchar(max)
Declare @Name_Edit nvarchar(max) 
Declare @Name1 as nvarchar(max)= N'B'
Declare @Price as nvarchar(max) = N'12'
Declare @NameTBL as nvarchar(max) = N'KeyBoard'
set @Name_Edit = N'A'
 set @TBL = N'TBL_Price'+ @NameTBL 
Set @sql = N'INSERT INTO [DB1].[dbo].'+quotename(@TBL) +'
 (
 [Name_Edit]
 ,[Name1]
 ,[Price]
 )
 VALUES
 (
 '+@Name_Edit+'
 ,'+@Name1+'
 ,'+@Price+'
 )'
 EXECUTE sp_executesql @sql
asked Feb 23, 2017 at 9:39

1 Answer 1

1

You're not quoting your strings properly.

When you insert a string, it has to be surrounded by single quotes, which in Dynamic SQL-ese, is three ticks. This should work.

DECLARE @sql AS NVARCHAR(MAX);
DECLARE @TBL AS NVARCHAR(MAX);
DECLARE @Name_Edit NVARCHAR(MAX); 
DECLARE @Name1 AS NVARCHAR(MAX)= N'B';
DECLARE @Price AS NVARCHAR(MAX) = N'12';
DECLARE @NameTBL AS NVARCHAR(MAX) = N'KeyBoard';
SET @Name_Edit = N'A';
SET @TBL = N'TBL_Price' + @NameTBL; 
SET @sql = N'INSERT INTO [DB1].[dbo].' + QUOTENAME(@TBL) + '
 (
 [Name_Edit]
 ,[Name1]
 ,[Price]
 )
 VALUES
 (
 ''' + @Name_Edit + '''
 ,''' + @Name1 + '''
 ,''' + @Price + '''
 )';
 PRINT ( @sql );
 --EXECUTE sp_executesql @sql

When I print the code, I get this.

INSERT INTO [DB1].[dbo].[TBL_PriceKeyBoard]
 (
 [Name_Edit]
 ,[Name1]
 ,[Price]
 )
 VALUES
 (
 'A'
 ,'B'
 ,'12'
 )
answered Feb 23, 2017 at 9:54
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.