子查询返回了多个值

时间:2013-04-02 09:32:41

标签: sql-server-2008

IF OBJECT_ID('Temp_expo') is not null
begin 
    drop table Temp_expo
end

set @query3 =  'SELECT SPCT_ID_REL_LOW,SPCT_ID_REL_HIGH,ROW_NUMBER() over (order by PDBC_PFX) as TempId  

INTO Temp_expo  
FROM ['+ @FCTServer +'].['+@FCTDBName+'].dbo.CMC_SPCT_SUPP_CONV  
where  SPCT_ID_REL_LOW <> '''' and SPCT_ID_REL_HIGH <> '''''

exec (@query3)

Select @minCount= min(TempId) from Temp_expo   
Select @maxCount= max(TempId) from Temp_expo  

create table #ICD9SPCT
(
    ICD9Code varchar(200)
} 

while @minCount<=@maxCount 
begin
    select @low=SPCT_ID_REL_LOW,@high=SPCT_ID_REL_HIGH 
    from Temp_expo 
    where TempId=@minCount 
    group by SPCT_ID_REL_LOW,SPCT_ID_REL_HIGH

    set  @loworder = (select ISNULL(OrderId,0) from FCT_ICD9_Diag_ORDER where ICD9=@low)
    set  @highorder = (select ISNULL(OrderId,0) from FCT_ICD9_Diag_ORDER where ICD9=@high)


    insert into #ICD9SPCT 
    select ICD9 from FCT_ICD9_Diag_ORDER ordert
    left join #ICD9SPCT icdorder on ordert.ICD9 = icdorder.ICD9Code
    where OrderId between @loworder and @highorder and icdorder.ICD9Code is null

    set @minCount = @minCount+1;
end

以上是我收到此错误的代码。我发现错误是由于以下代码plz帮助

set  @loworder = (select ISNULL(OrderId,0) from FCT_ICD9_Diag_ORDER where ICD9=@low)
set  @highorder = (select ISNULL(OrderId,0) from FCT_ICD9_Diag_ORDER where ICD9=@high)

1 个答案:

答案 0 :(得分:0)

set  @loworder = (select ISNULL(OrderId,0) from FCT_ICD9_Diag_ORDER where ICD9=@low)
set  @highorder = (select ISNULL(OrderId,0) from FCT_ICD9_Diag_ORDER where ICD9=@high)

您可以将其重写为

select @loworder = ISNULL(OrderId,0) from FCT_ICD9_Diag_ORDER where ICD9=@low
select @highorder = ISNULL(OrderId,0) from FCT_ICD9_Diag_ORDER where ICD9=@high

如果您确定根据标准只有一个值,并且您只需要一个值。如果有多个记录,那么你需要它们

SET  @loworder = STUFF(
       (select DISTINCT ';' + CAST(OrderId AS varchar(20))
       FROM FCT_ICD9_Diag_ORDER where ICD9=@low FOR XML PATH ('')
       ),1,1, '')

@loworder应该是varchar(max)

我希望它有所帮助!