SQL SERVER - COALESCE() 函数的问题

发布于 2024-11-15 08:42:08 字数 675 浏览 3 评论 0原文

我有一个由存储过程包装的 SQL 函数:

ALTER FUNCTION dbo.GetObjList
(
    @filterUID int = NULL,
    @filterSID varchar(32) = NULL
)
RETURNS TABLE
AS

RETURN 

SELECT ROW_NUMBER() OVER (ORDER BY UID) AS [RowNumber], * 
FROM ObjTable
WHERE 
    (COALESCE(@filterUID, @filterSID) IS NULL) OR 
    (
        ((@filterUID IS NOT NULL) AND (UID = @filterUID)) OR
        ((@filterSID IS NOT NULL) AND (SID = @filterSID))
    )

为什么我会收到这样的错误:“将 varchar 值 'abc' 转换为数据类型 int 时转换失败。” 如果我仅传递 < code>@filterSID = 'abc' 作为参数(其他参数为默认值)?

我注意到 COALESCE 是造成该错误的原因。

编辑:现在我知道了错误的原因......并且考虑到我实际上有很多参数......你们会推荐什么作为解决方案?

I have this SQL function which is wrapped by a stored procedure:

ALTER FUNCTION dbo.GetObjList
(
    @filterUID int = NULL,
    @filterSID varchar(32) = NULL
)
RETURNS TABLE
AS

RETURN 

SELECT ROW_NUMBER() OVER (ORDER BY UID) AS [RowNumber], * 
FROM ObjTable
WHERE 
    (COALESCE(@filterUID, @filterSID) IS NULL) OR 
    (
        ((@filterUID IS NOT NULL) AND (UID = @filterUID)) OR
        ((@filterSID IS NOT NULL) AND (SID = @filterSID))
    )

Why would I receive such an error: "Conversion failed when converting the varchar value 'abc' to data type int." if I pass only @filterSID = 'abc' as parameters (and DEFAULT for others) ?

I noticed that COALESCE is responsible for the error.

EDIT: Now that I got the reason of the error... and given the fact that I have lots of params actually... what would you guys recommend as solution?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

硬不硬你别怂 2024-11-22 08:42:08

合并

返回类型

返回具有最高数据类型优先级的表达式的数据类型。如果所有表达式均不可为空,则结果类型为不可为空。

(强调是后加的)。 int 的优先级比 varchar 更高,因此 < 的返回类型code>COALESCE 必须是 int 类型。显然,你的 varchar 值不能这样转换。

您可以将 where 子句重写为:

WHERE 
    (@filterUID IS NULL AND @filterSID IS NULL) OR 
    (@filterUID IS NOT NULL AND UID = @filterUID) OR
    (@filterSID IS NOT NULL AND SID = @filterSID)

COALESCE:

Return Types

Returns the data type of expression with the highest data type precedence. If all expressions are nonnullable, the result is typed as nonnullable.

(Emphasis added). int had a higher precedence than varchar, so the return type of your COALESCE must be of type int. And obviously, your varchar value cannot be so converted.

You can re-write your where clause simply as:

WHERE 
    (@filterUID IS NULL AND @filterSID IS NULL) OR 
    (@filterUID IS NOT NULL AND UID = @filterUID) OR
    (@filterSID IS NOT NULL AND SID = @filterSID)

尝试将 Coalesce 中的参数转换为 Varchar
例如:

(COALESCE(CONVERT(VARCHAR,@filterUID), CONVERT(VARCHAR,@filterSID)) IS NULL) OR 

Try converting the parameters in Coalesce to Varchar
For instance:

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