自动转换或其他东西..动态sql更新
我在存储过程中有动态sql:
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
问题是我不知道@task_field_name表示的字段是bigint还是nvarchar,所以我得到转换错误:
Error converting data type nvarchar to bigint.
如何防止该错误?
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)
我能想到的只有两种情况会给你这个错误消息。
数据库中的字段task_id实际上并不是bigint。如果它是 varchar 并包含类似 ''(空白字符串)的内容,则 WHERE 子句可能会失败,因为该列正在与 bigint 变量 @task_id 进行比较。
@task_field_name 设置为 bigint 列,@value 中的值不可转换为 bigint。这肯定是一个编程错误,因为只要给出正确的输入,TSQL 代码实际上就可以正常工作 - 这就是 Martin 试图向您展示的内容。
对于 (2),假设 @value 包含字符串“A”。并且您要求用该值更新 bigint 列 - 它肯定会失败!?如果 @value 包含任何有效的 bigint 值(即使在 nvarchar(50) 变量中),则代码可以工作。
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.
不要使用动态 SQL,也不要尝试编写通用的 UPDATE 代码。正如您发现的那样,它不会节省您任何时间,现在您必须在这里询问。
要么组合成一个……
要么分开就
我个人而言,我也不会将通用的@value作为参数。我有单独的代码或传递两个参数,每列一个。
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.