我有以下标量函数,此函数比较一个用户与另一个用户之间的值,如果它们匹配则返回true,否则为false。
功能如下:
SELECT TOP 1 CASE WHEN us.UserId IS NULL THEN 0 ELSE 1 END AS does_data_match
FROM [User].[User_Profile] up
INNER JOIN [User].[User_Details] d ON up.Id = d.UserId
LEFT OUTER JOIN [user].[User_Settings] us
ON us.UserId = @UserId1
AND d.Height between ISNULL(us.HeightFrom, d.height) and ISNULL(us.HeightTo, d.Height)
AND up.Age between ISNULL(us.AgeFrom, up.age) and ISNULL(us.AgeTo, up.Age)
AND up.Gender = ISNULL(us.Gender, up.Gender)
WHERE up.id = @UserId2
ORDER BY up.id ASC
我对此函数的问题偶尔是User.User_Settings不包含@ UserId1的记录所以默认情况下应该返回1允许@ UserId2联系它们,但由于case语句它返回0,我在我的case语句中切换了0和1,但这样做会导致函数在设置表中存在@ UserId1时返回不正确的结果。
我试图使用If语句来调整它,以检查用户设置表中是否退出@ UserId1然后运行case语句,否则选择1(true)作为默认值。
但由于某种原因它不允许我在标量函数中有一个If语句?
任何帮助都将不胜感激。
更新
当我将其包装在IF语句
中时,这就是我的casestatementIF EXISTS(Select Userid from [user].[User_Settings] where UserId = @UserId1)
BEGIN
SELECT TOP 1 CASE WHEN us.UserId IS NULL THEN 0 ELSE 1 END AS does_data_match
FROM [User].[User_Profile] up
INNER JOIN [User].[User_Details] d ON up.Id = d.UserId
LEFT OUTER JOIN [user].[User_Settings] us
ON us.UserId = @UserId1
AND d.Height between ISNULL(us.HeightFrom, d.height) and ISNULL(us.HeightTo, d.Height)
AND up.Age between ISNULL(us.AgeFrom, up.age) and ISNULL(us.AgeTo, up.Age)
AND up.Gender = ISNULL(us.Gender, up.Gender)
WHERE up.id = @UserId2
ORDER BY up.id ASC
END
ELSE
BEGIN
return 1
END
但如上所述,我收到以下错误消息
附近的语法不正确答案 0 :(得分:2)
首先使用IF条件检查“设置”表中是否存在@ UserId1。如果不是,请返回所需的值。如果记录确实存在,请检查ID是否匹配并返回所需的值。
这应该简单易行。
ALTER FUNCTION [dbo].[CheckFunction]
(
-- Add the parameters for the function here
@UserID1 int
)
RETURNS BIT
AS
BEGIN
DECLARE @ReturnCode BIT
IF (@UserID1 = 1)
BEGIN
SET @ReturnCode = 1
END
ELSE
BEGIN
SET @ReturnCode = 0
END
RETURN @ReturnCode
END
GO
执行功能:
SELECT [dbo].[CheckFunction] ( 0 ) --returns 0 (expected)
SELECT [dbo].[CheckFunction] ( 1 ) --returns 1 (expected)
答案 1 :(得分:0)
所以看起来用户没有进入用户设置,id将始终为null,但如果输入了用户,那么ID将永远不会为null,所以试试这个:
String selectQuery = "SELECT * FROM " + SAP_DRQ_TABLE +" where "+SAP_DRQ_KEY_METROLAC+"='50'"