automatic casting or somethig.. update in dynamic sql

发布于 2022-09-06 08:35:19 字数 773 浏览 14 评论 0

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

猫瑾少女 2022-09-13 08:35:20

There are only 2 cases I can think of that will give you that error message.

  1. 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.

  2. @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.

〆凄凉。 2022-09-13 08:35:20

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...

UPDATE
   dbo.T_CUS_TSK_TASK
SET
   bigintColumn = CASE WHEN @task_field_name = 'bigintColumn'
                                   THEN CAST(@value AS bigint) ELSE bigintColumn END
   nvarcharColumn = CASE WHEN @task_field_name = 'nvarcharColumn'
                                   THEN @value ELSE nvarcharColumn END
WHERE
   company_id = @company_id AND task_id = @task_id

...or separate

IF @task_field_name = 'bigintColumn'
    UPDATE
       dbo.T_CUS_TSK_TASK
    SET
       bigintColumn = CAST(@value AS bigint)
    WHERE
       company_id = @company_id AND task_id = @task_id
ELSE
    UPDATE
       dbo.T_CUS_TSK_TASK
    SET
       nvarcharColumn = @value
    WHERE
       company_id = @company_id AND task_id = @task_id

Personally, I wouldn't have generic @value as a parameter either. I'd have separate code or pass in two parameters, one per column.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文