SQL SERVER - COALESCE() 函数的问题
我有一个由存储过程包装的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
合并
:(强调是后加的)。 int 的优先级比 varchar 更高,因此 < 的返回类型code>COALESCE 必须是 int 类型。显然,你的 varchar 值不能这样转换。
您可以将 where 子句重写为:
COALESCE
:(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:
尝试将
Coalesce
中的参数转换为Varchar
例如:
Try converting the parameters in
Coalesce
toVarchar
For instance: