I have a stored procedure that select * from book table
, using sub query my query is
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)
I know sub query is return more than one query to main query , But i don't know how to avoid this error, can any one help me ?
This question is related to
sql-server
subquery
The problem is that these two queries are each returning more than one row:
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
You have two choices, depending on your desired outcome. You can either replace the above queries with something that's guaranteed to return a single row (for example, by using SELECT TOP 1
), OR you can switch your =
to IN
and return multiple rows, like this:
select * from dbo.books where isbn IN (select isbn from dbo.lending where (act between @fdate and @tdate) and (stat ='close'))
Use In
instead of =
select * from dbo.books
where isbn in (select isbn from dbo.lending
where act between @fdate and @tdate
and stat ='close'
)
or you can use 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' )
You can use IN operator as below
select * from dbo.books where isbn IN
(select isbn from dbo.lending where lended_date between @fdate and @tdate)
Source: Stackoverflow.com