我有两张桌子。一个是参考表,其中包含一组字符串名称TubName
:
| Id | SiteID | TubName | TubVol |
|----|---------|---------|--------|
| 1 | Site001 | Tub 1 | 1000 |
| 2 | Site001 | Tub 2 | 1000 |
| 3 | Site001 | Tub 3 | 1000 |
| 4 | Site001 | Tub 4 | 1000 |
| 5 | Site001 | Tub 5 | 1000 |
| 6 | Site001 | Tub 6 | 1000 |
每天都会生成一份报告,显示哪些TubName
存在:
| Id | SiteID | Date | Tub |
|----|---------|----------|-------|
| 1 | Site001 | 20/06/15 | Tub 1 |
| 2 | Site001 | 20/06/15 | Tub 1 |
| 3 | Site001 | 20/06/15 | Tub 3 |
| 4 | Site001 | 20/06/15 | Tub 4 |
| 5 | Site001 | 20/06/15 | Tub 5 |
如果比较两个表,则Tub 2
和Tub 6
不存在。
我创建了一个简单的查询,它返回"未经测试的"桶:
SELECT r.TubName
FROM Tubs r
WHERE TubName NOT IN(SELECT b.Tub FROM Tests b where SiteID = 'Site001' AND Date = '20/06/15')
我真正想要的是一个函数,我可以通过编程方式输入SiteID
和Date
作为参数。我尝试过这样的事情:
CREATE FUNCTION [dbo].[TubsNotTested](@id nvarchar(128), @testdate nvarchar(MAX))
RETURNS view
AS
BEGIN
RETURN (
SELECT r.TubName
FROM [dbo].[Tubs] r
WHERE TubName NOT IN(
SELECT b.Tub
FROM dbo.Tests b
where(SiteID = id AND Date = testdate)
)
)
END
但是当table
是返回的对象时,我收到错误:
带有返回值的RETURN语句不能在此上下文中使用。
或者,当我尝试返回View
:
关键字'视图'附近的语法不正确。
答案 0 :(得分:3)
你可以尝试这样的事情:
CREATE FUNCTION [dbo].[TubsNotTested](@id nvarchar(128), @testdate nvarchar(MAX))
RETURNS TABLE
AS RETURN(
SELECT r.TubName
FROM [dbo].[Tubs] r
LEFT JOIN (
SELECT b.Tub
FROM dbo.Tests b
WHERE (SiteID = @id AND Date = @testdate)
) as tubs
ON r.TubName = b.Tub
WHERE tubs.Tub IS NULL
)
如果您需要在函数中加入更多逻辑,可以构建多语句函数:
CREATE FUNCTION [dbo].[TubsNotTested](@id nvarchar(128), @testdate nvarchar(MAX))
RETURNS @result TABLE(
TubName nvarchar(50)
)
AS
BEGIN
INSERT INTO @result(TubName)
SELECT r.TubName
FROM [dbo].[Tubs] r
LEFT JOIN (
SELECT b.Tub
FROM dbo.Tests b
WHERE (SiteID = @id AND Date = @testdate)
) as tubs
ON r.TubName = b.Tub
WHERE tubs.Tub IS NULL
RETURN
END
顺便说一下。小心。 SQL Server功能,可能是更大请求的瓶颈。记住这一点。
答案 1 :(得分:1)
除RETURNS view
外,您还需要正确指定参数:
CREATE FUNCTION [dbo].[TubsNotTested](@id nvarchar(128), @testdate nvarchar(MAX))
RETURNS TABLE
AS
RETURN(SELECT r.TubName
FROM [dbo].[Tubs] r
WHERE TubName NOT IN (
SELECT b.Tub
FROM dbo.Tests b
where(SiteID = @id AND Date = @testdate)
)
);
对于内联表值函数,BEGIN
/ END
是不必要的。