Ros*_*han 14 sql-server subquery
我有一个存储过程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)
Run Code Online (Sandbox Code Playgroud)
我知道子查询返回多个查询到主查询,但我不知道如何避免这个错误,任何人都可以帮助我吗?
Dan*_*zey 24
问题是这两个查询都返回多行:
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
Run Code Online (Sandbox Code Playgroud)
根据您的预期结果,您有两种选择.您可以使用保证返回单行的内容替换上述查询(例如,通过使用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'))
Run Code Online (Sandbox Code Playgroud)
pra*_*een 10
用In而不是=
select * from dbo.books
where isbn in (select isbn from dbo.lending
where act between @fdate and @tdate
and stat ='close'
)
Run Code Online (Sandbox Code Playgroud)
或者你可以使用 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' )
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
168181 次 |
| 最近记录: |