存储过程中的动态游标

时间:2011-07-23 11:43:24

标签: c# sql-server-2005 programming-languages

嗨我正在执行一个包含游标的存储过程...游标有一个动态的sql查询..这个查询有动态值..这是@ industry..then我把结果放在一个临时表中..但是问题是当我执行程序结果没有来......

这是我在sqlserver

中的stroedproc
ALTER PROCEDURE GETARTISTDETAIL  AS
BEGIN
    DECLARE @INDUSTRY VARCHAR(40)
    DECLARE @ID INT
    DECLARE @SQL1 VARCHAR(1000)
    DECLARE @SQL VARCHAR(1000)
    SET @INDUSTRY='''BollyWood'',''TollyWood'',''HollyWood'''
CREATE TABLE #TEMPTBL([NAME] VARCHAR(20),[AGE] INT ,[MAILID] VARCHAR(20))   
    --SET @SQL='SELECT ARTISTID FROM ARTIST WHERE INDUSTRY IN ('+@INDUSTRY+')' 
    DECLARE TEMPCRS CURSOR LOCAL SCROLL STATIC FOR SELECT ARTISTID FROM ARTIST WHERE INDUSTRY IN (@INDUSTRY)
    --PRINT @SQL
    --exec (@SQL)
    OPEN TEMPCRS
    FETCH NEXT FROM TEMPCRS INTO  @ID
    WHILE @@FETCH_STATUS=0  
    BEGIN
    INSERT INTO #TEMPTBL SELECT [NAME],[AGE],[MAILID] FROM ARTIST WHERE ARTISTID=@ID
    FETCH NEXT FROM TEMPCRS INTO  @ID
    END
    CLOSE TEMPCRS
    DEALLOCATE TEMPCRS
    SELECT * FROM #TEMPTBL
    DROP TABLE #TEMPTBL
END

1 个答案:

答案 0 :(得分:2)

您不需要游标来执行此操作,只需使用子查询:

DECLARE @INDUSTRY VARCHAR(40)
DECLARE @SQL VARCHAR(1000)

CREATE TABLE #TEMPTBL([NAME] VARCHAR(20),[AGE] INT ,[MAILID] VARCHAR(20))  

SET @INDUSTRY='''BollyWood'',''TollyWood'',''HollyWood'''

SET @SQL='INSERT INTO #TEMPTBL SELECT [NAME],[AGE],[MAILID] 
          FROM ARTIST WHERE ARTISTID IN (
            SELECT ARTISTID FROM ARTIST WHERE INDUSTRY IN ('+@INDUSTRY+')
         )' 

EXEC (@SQL)

SELECT * FROM #TEMPTBL
DROP TABLE #TEMPTBL