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 ?
Answer: This error message appears when you try to use subquery (correlated or not) that returns more than one value to the calling query. This usually indicates that there are duplicate entries in the column of a table where it's expected to be unique.
This is not permitted when the subquery follows =, != , <, <= , >, >= or when the subquery is used as an expression.
The operators used in a single-row subqueries relational operators (=, <>, >, >=, <, <=) cannot be used in multiple-row subqueries.
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' )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With