将输入参数作为列名传递以更新存储过程中的列值

时间:2017-10-09 18:57:42

标签: sql sql-server stored-procedures

我有一个存储过程insertvalue,包含以下三个参数:

@stdrollno int,
@sem int,
@IsCheck int,
@subjectname varchar(100),
@test varchar(100)

我有一个表demo,其中有一个名为defaulter的表,其中有一列

[Microprocessor th] varchar(50)
[Structured and Object Oriented Analysis and Design th] varchar(50)

我必须更新其值。

所以在我的存储过程insertvalue中,我写了这个SQL代码:

if(@sem = 5)
     BEGIN
        BEGIN
            declare @sql3 nvarchar(500);
            set @sql3 = 'update TEdefaulters 
                        set ['+CAST(@test as nvarchar(100))+'] = ['+CAST(@test as nvarchar(100))+']  + '+CAST(@IsCheck as nvarchar(100))+' 
                        where stdrollno = ' +CAST(@stdrollno as nvarchar(100));

            exec sp_executesql @sql3
          END
          BEGIN
             update TEdefaulters
             set total_theory = total_theory + CONVERT(INT, @ischeck)
             where stdrollno = @stdrollno
          END
          BEGIN
             update TEdefaulters
             set total_attendance = total_attendance + CONVERT(INT, @ischeck)
             where stdrollno = @stdrollno
          END
          BEGIN
                 update TEdefaulters
                 set theory_percentage = (cast((Select total_theory from TEdefaulters where stdrollno=@stdrollno ) as float) / (cast((Select total_theory from TEdefaulters where stdname='total' ) as float))) * 100
                 where stdrollno=@stdrollno
          END
           BEGIN
               update TEdefaulters
              set attendance_percentage = (cast((Select total_attendance from TEdefaulters where stdrollno=@stdrollno ) as float)  /(cast((Select total_attendance from TEdefaulters where stdname='total' )as float))) * 100
              where stdrollno=@stdrollno
          END
      END

但它不起作用,它会导致错误 有效的价值是:

exec inserttheoryattendance 5 , 5 , 1 , 'Microprocessor', 'Microprocessor th'

不起作用的值是

exec inserttheoryattendance 5 , 5 , 1 , 'Structured and Object Oriented Analysis and Design', 'Structured and Object Oriented Analysis and Design th'
  

无法将nvarchar转换为int

1 个答案:

答案 0 :(得分:0)

  

声明@sql nvarchar(50);

对于SQL字符串,50个字符太短。尝试将其更改为nvarchar(500)