我有三张牌桌:File
,Word
和WordInstance
:
CREATE TABLE [dbo].[File](
[FileId] [int] IDENTITY(1,1) NOT NULL,
[FileName] [nchar](10) NOT NULL)
CREATE TABLE [dbo].[Word](
[WordId] [int] IDENTITY(1,1) NOT NULL,
[Word] [nchar](10) NOT NULL,
[LatestFileId] [int] NOT NULL)
CREATE TABLE [dbo].[WordInstance](
[WordInstanceId] [int] IDENTITY(1,1) NOT NULL,
[WordId] [int] NOT NULL,
[FileId] [int] NOT NULL)
请注意,我省略了外键以简化此操作。给定FileId
我想返回一个true / false值,告诉我是否有其他文件与指定的FileId
具有相同的单词。
从这开始,我知道它不起作用,但按原样提供:
CREATE FUNCTION [dbo].[DoesFileContainLastWord]
(
@fileId INT
)
RETURNS BIT
AS
BEGIN
DECLARE @count INT
DECLARE @ret BIT
SELECT @count = COUNT([tW].[WordId])
FROM [Word] AS tW
INNER JOIN [WordInstance] AS tWI
ON [tW].[WordId] = [tWI].[WordId]
INNER JOIN [File] AS tF
ON [tF].[FileId] = [tW].[LatestFileId]
WHERE [tF].[FileId] = @fileId
IF @count > 0
BEGIN
SET @ret = 0
END
ELSE
SET @ret = 1
RETURN @ret
END;
答案 0 :(得分:1)
在SQL Server 2005上测试:
declare @file table (fileid int)
declare @instance table (fileid int,wordid int)
insert into @file (fileid)
select 1 union all select 2
insert into @instance (fileid,wordid)
select 1,1
union all select 1,2
union all select 1,3
union all select 2,1
union all select 2,2
declare @fileid int
set @fileid=2
;with fvalues as
(
select distinct wordid from @instance where fileid=@fileid
)
select case when exists
(
select *
from fvalues v
inner join @instance i on v.wordid = i.wordid
and i.fileid<>@fileid
group by i.fileid
having count(distinct i.wordid) >= (select count(*) from fvalues)
)
then cast(1 as bit)
else cast(0 as bit) end
@fileid=1
返回0,@fileid=2
返回1,因为文件1的字集是文件2的正确超集。