automatic casting or somethig.. update in dynamic sql
I have dynamic sql in stored procedure:
DECLARE @sql nvarchar(1000)
SET @sql = 'UPDATE dbo.T_CUS_TSK_TASK '+
'SET ' + QUOTENAME(@task_field_name) + '=@value ' +
'WHERE company_id=@company_id AND task_id=@task_id'
print(@sql)
EXEC sp_executesql
@sql,
N'@company_id uniqueidentifier, @task_id bigint, @value nvarchar(50)',
@company_id, @task_id, @value
the problem is that I don't know if the field represented by @task_field_name is bigint or nvarchar so I get converting error:
Error converting data type nvarchar to bigint.
How can I prevent the error?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
There are only 2 cases I can think of that will give you that error message.
The field task_id in the database is not actually bigint. If it is varchar and contains something like '' (blank string), then the WHERE clause can fail because the column is being compared to a bigint variable @task_id.
@task_field_name is set to a bigint column, and the value in @value is not convertible to a bigint. This is surely a programming error, because the TSQL code actually works fine as long as it is given proper input - this is what Martin is trying to show you.
Re (2), let's say @value contains the string 'A'. And you have asked to update a bigint column with that value - surely it should fail!? If @value contained any valid bigint value (even within a nvarchar(50) variable) the code does work.
Don't use dynamic SQL and don't try to write generic UPDATE code. It doesn't save you any time, as you've found out and now you've had to ask here.
Either combine into one...
...or separate
Personally, I wouldn't have generic @value as a parameter either. I'd have separate code or pass in two parameters, one per column.