2013-04-17 22 views
11

我有一個存儲過程select * from book table,使用子查詢我的查詢是子查詢返回多個值。當子查詢遵循=,!=,<,<=,>,> =或當子查詢用作表達式時,這是不允許的。

USE [library] 
GO 

/****** Object: StoredProcedure [dbo].[report_r_and_l] Script Date: 04/17/2013 12:42:39 ******/ 

SET ANSI_NULLS ON 
GO 

SET QUOTED_IDENTIFIER ON 
GO 

ALTER procedure [dbo].[report_r_and_l] 
@fdate date, 
@tdate date, 
@key varchar(1) 
as 

if(@key='r') 

    select * 
    from dbo.books 
    where isbn =(select isbn from dbo.lending where (act between @fdate and @tdate) and (stat ='close')) 

else if(@key='l') 

    select * 
    from dbo.books 
    where isbn =(select isbn from dbo.lending where lended_date between @fdate and @tdate) 

我知道子查詢是返回多個查詢主要查詢,但我不知道如何避免這個錯誤,任何人都可以幫助我嗎?

+0

顯然'select isbn'返回多個值。你可以使用'where isbn IN(select isbn ...' –

回答

25

的問題是,這兩個查詢每個返回不止一個行:

select isbn from dbo.lending where (act between @fdate and @tdate) and (stat ='close') 
select isbn from dbo.lending where lended_date between @fdate and @tdate 

根據您的預期結果,您有兩種選擇。您可以用東西是保證返回一個行(例如,通過使用SELECT TOP 1)替換上述疑問,或者您可以將您的=IN和返回多行,像這樣:

select * from dbo.books where isbn IN (select isbn from dbo.lending where (act between @fdate and @tdate) and (stat ='close')) 
+0

我知道我的朋友Thankz。我想知道關於此的一件事,只有一個是在books表中引用選定的isbn,我想從貸款表中選擇isbn,lend_no從貸款表sudent_name中從學生表中引用表中的索引號,如何檢索多個來自多個表的行? – Roshan

+0

很明確的答案@丹。 – Ads

+1

它應該是lent_date而不是lended_date。 我只是說... – sanepete

4

您可以使用IN操作符如下

select * from dbo.books where isbn IN 
(select isbn from dbo.lending where lended_date between @fdate and @tdate) 
8

使用In而不是=

select * from dbo.books 
where isbn in (select isbn from dbo.lending 
       where act between @fdate and @tdate 
       and stat ='close' 
       ) 

,或者您可以使用Exists

SELECT t1.*,t2.* 
FROM books t1 
WHERE EXISTS (SELECT * FROM dbo.lending t2 WHERE t1.isbn = t2.isbn and 
       t2.act between @fdate and @tdate and t2.stat ='close') 
+0

thnx bro。u save my day:)。你應該得到一罐特大啤酒。 – Kings

+0

SET atRate1 =(SELECT t1。*,t2。* FROM RateCode t1 WHERE EXISTS(SELECT * FROM RateAmount t2 WHERE t1.RateCode = t2.RateCode AND t1.CountryCode = @Code AND t1.ModuleCode = @MCode)) 我得到t2的錯誤。* –

相關問題