我一直在尝试创建此函数时遇到无法将数据返回给客户端的错误,我只想通过查询表然后检查@@来了解如何执行以下操作。 ROWCOUNT并根据结果设置位值,如何在不过于复杂的情况下执行此操作?
RETURNS BIT
AS
BEGIN
-- Set @sDup to False
DECLARE @sDup BIT = 0
--check allDataTemp
SELECT * FROM tbl1 JOIN ON tbl8 WHERE fld1 = @val1 and fld2 = @val2
and fld3 = @val4
IF (@@ROWCOUNT > 0)
BEGIN
SET @sDup = 1
RETURN @sDup
END
--check allDataTemp2
SELECT * FROM tbl2
IF (@@ROWCOUNT > 0)
BEGIN
SET @sDup = 1
RETURN @sDup
END
SELECT * FROM tbl3
IF (@@ROWCOUNT > 0)
BEGIN
SET @sDup = 1
RETURN @sDup
END
-- Return the result of the function
RETURN @sDup
答案 0 :(得分:1)
问题是你正在尝试选择数据,当它只期望返回BIT值时,它试图输出该选择的结果。请重新尝试使用您的查询:
RETURNS BIT
AS
BEGIN
-- Set @sDup to False
DECLARE @sDup BIT = 0
--check allDataTemp
IF (SELECT COUNT(*) FROM tbl1) > 0
BEGIN
SET @sDup = 1
RETURN @sDup
END
--check allDataTemp2
IF (SELECT COUNT(*) FROM tbl2) > 0
BEGIN
SET @sDup = 1
RETURN @sDup
END
IF (SELECT COUNT(*) FROM tbl3) > 0
BEGIN
SET @sDup = 1
RETURN @sDup
END
-- Return the result of the function
RETURN @sDup
END
上面稍微更简洁的版本保持相同的短路逻辑,如下所示:
BEGIN
-- Set @sDup to False
DECLARE @sDup BIT = 0
-- Collect Data and perform logic
SET @sDup = (CASE
WHEN (SELECT COUNT(*) FROM tbl1) > 0 THEN 1
WHEN (SELECT COUNT(*) FROM tbl2) > 0 THEN 1
WHEN (SELECT COUNT(*) FROM tbl3) > 0 THEN 1
ELSE 0 END)
--Return Value
RETURN @sDup
END
答案 1 :(得分:1)
RETURNS BIT
AS
BEGIN
-- Set @sDup to False
DECLARE @sDup BIT = 0
--check allDataTemp
IF EXISTS (SELECT * FROM tbl1)
BEGIN
SET @sDup = 1
RETURN @sDup
END
--check allDataTemp2
IF EXISTS (SELECT * FROM tbl2)
BEGIN
SET @sDup = 1
RETURN @sDup
END
IF EXISTS (SELECT * FROM tbl3)
BEGIN
SET @sDup = 1
RETURN @sDup
END
-- Return the result of the function
RETURN @sDup
由于您只检查是否存在任何行,因此使用带有EXISTS
的{{1}}将为您提供最佳性能,因为它将停止执行并在第一次命中后立即返回True,< / p>
答案 2 :(得分:0)
您为每个表创建一个计数,设置每个总计的变量,然后只检查一个变量是否为0或者大于0然后返回1