简体   繁体   中英

I can't insert into table in SQL Server

I created a stored procedure which has two statements insert and update .

It gets two parameters:

@content as nvarchar(10),
@fieldName as int

In Update line everything works correctly, but it doesn't insert to table. Syntax and everything is true but when I execute

Execute sp_update 432,4

SQL Server shows this error:

Msg 207, Level 16, State 1, Line 1
Invalid column name 'up'.
Msg 207, Level 16, State 1, Line 1
Invalid column name 'Field3'.

This is my script:

ALTER procedure [dbo].[sp_update]
    @content as nvarchar(10),
    @fieldName as int
as
   declare @ff as varchar
   set @ff = Convert(varchar,@fieldName)

   declare @f as char(7) 
   set @f = 'Field'+ @ff

   declare @sqlupdate varchar(500)
   declare @sqlinserttoChangelog varchar(500)

   set @sqlinserttoChangelog = 'Insert Into dbo.changelog (changeType, fieldname) Values ('+'up'+','+@f+')'
   Exec (@sqlinserttoChangelog)

   set @sqlupdate = 'update TableTest set ' + @f + ' = '+@Content
   Exec (@sqlupdate)

Since you are creating dynamic sql , the values should be wrap with single quote. To escape single quote, it must be doubled, eg.

set @sqlinserttoChangelog = 'Insert Into dbo.changelog (changeType, fieldname) Values ('''+'up'+''', '+@f+')'

same with the content

set @sqlupdate = 'update TableTest set ' + @f + ' = '''+ @Content + ''''

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