Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 2008 返回多个表的SQL游标_Sql Server 2008 - Fatal编程技术网

Sql server 2008 返回多个表的SQL游标

Sql server 2008 返回多个表的SQL游标,sql-server-2008,Sql Server 2008,我有一个sql存储过程,其中我使用一个游标,其中包含select语句中的一组id,我使用这些id逐个检查,使用游标将值放入其他变量,并使用这些变量进行sql连接。我的问题是,当我执行此操作时,返回了许多表,而我只需要返回一个表 SET NOCOUNT ON declare @BSVal as int declare @GSVal as int declare @mID as int declare @qID as int DECLARE M_Cursor cursor for sele

我有一个sql存储过程,其中我使用一个游标,其中包含select语句中的一组id,我使用这些id逐个检查,使用游标将值放入其他变量,并使用这些变量进行sql连接。我的问题是,当我执行此操作时,返回了许多表,而我只需要返回一个表

SET NOCOUNT ON


declare @BSVal as int
declare @GSVal as int

declare @mID as int
declare @qID as int

DECLARE M_Cursor cursor for

select 
ms.MID,ms.QID
from  vM As ms join QS as qs
ON ms.QSID=qs.QIDjoin 
Mar as mar on mar.MarID=qs.MarID
where (ms.Cid='Web')

open M_Cursor

FETCH NEXT FROM M_Cursor 
INTO @mID, @qID


--Get values
WHILE @@FETCH_STATUS = 0
BEGIN
set @BSVal= (select top 1 SCID from vSC where (EnID in 
(select EnID from En where EnName='BAIDU')
and QTID=1 and MID=@mIDand QSID=@qID)order by ITime desc); 
set @GSVal= (select top 1 SCID from vSC where ( EnID in 
(select EnID from En where EnName='GRAPHIC') and QTID=1 
and MID=@mIDand QSID=@QSID) order by ITime desc);




select  * from 

vM m 

join vw5TABLE BNDCG on (m.QSid=BNDCG.QID And BNDCG.Position=1) 
join vw5TABLE GNDCG on (m.QSid=GNDCG.QID And GNDCG.Position=1)

where

BNDCG.SCid=@BSVal
and GNDCG.SCid=@GSVal
and BNDCG.QSID=@ qID
and GNDCG.QSID=@ qID
and m.MID=@mID




FETCH NEXT FROM M_Cursor 
   INTO @MID, @QSID


END
CLOSE M_Cursor;
DEALLOCATE M_Cursor;

该代码将为游标的每次迭代运行select,这使它看起来像“许多表”。听起来您需要将该选择的结果插入到临时表或游标内的表变量中,然后在游标完成后,从该临时表中选择一次。我还没有详细阅读您的代码,但我猜这可能不需要光标

这是一个使用表变量的粗略示例

DECLARE @temptable  TABLE (col1 INT, Col2 VARCHAR(3), Col3 INT)


insert into @temptable (col1,col2,col3)
select  (col1,col2,col3) from 
vM m 
join vw5TABLE BNDCG on (m.QSid=BNDCG.QID And BNDCG.Position=1) 
join vw5TABLE GNDCG on (m.QSid=GNDCG.QID And GNDCG.Position=1)
where
BNDCG.SCid=@BSVal
and GNDCG.SCid=@GSVal
and BNDCG.QSID=@ qID
and GNDCG.QSID=@ qID
and m.MID=@mID

....
..

DEALLOCATE M_Cursor;

SELECT Col1,Col2,Col3 FROM @temptable

谢谢听起来不错,我将按照您的建议实现一个临时表。另外一个相关问题是,查询返回空行,以及如何避免在输出中获取空行,这是为每个条件添加is NOT null的唯一方法——感谢您不介意上面的问题,在使用临时表方法之后,没有返回空行。