2012-07-18 5 views
0

많은 슈퍼 세트에 많은 찾기 : File, WordWordInstance :나는 세 개의 테이블이 SQL 서버

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을 지정하면 FileId과 같은 단어를 가진 다른 파일이 있는지를 알려주는 true/false 값을 반환하고 싶습니다. 이 시작

, 나는 그대로 작동하지만 제공되지 않습니다 알고

2005 SQL 서버에서 테스트
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; 
+2

그래서 무엇을 시도 했습니까? 이것은 당신이 알고있는 코드 작성 서비스가 아닙니다. – HLGEM

답변

1

: 파일로, @fileid=2에 대한 @fileid=1 및 1

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 [email protected] 
) 
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 

반환 0 1의 단어 집합은 파일 2의 적절한 수퍼 집합입니다.

+0

예상대로 작동합니다! 사용할 옵션이 있는지 궁금해하면 구문에 간단히 적용하십시오. – Icerman

+0

@Icerman - 중첩 된 서브 쿼리로 CTE를 변경하고,'CASE' 블록과 외부 선택을 제거하고,'*'를'i.fileid'로 대체하여 내부 쿼리의 결과를 리턴합니다. 그런 다음 TVF에 넣고 'CROSS APPLY'를 사용하여 단어 수퍼 집합을 가진 파일을 필터링 할 수 있습니다. –

관련 문제