光标的等效设置基本查询

时间:2016-03-16 14:20:29

标签: sql sql-server tsql stored-procedures cursor

我有一个使用游标的存储过程。我想知道光标的任何等效的set base查询。

USE [T04_676]
GO

/****** Object:  StoredProcedure [dbo].[proc_InsertAssessmentCast]    Script Date: 3/16/2016 7:43:44 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO






-- =============================================
-- Author:      <Capgemini>
-- Create date: <12-Mar-2016>
-- Description: <This Stored procedure is used to create table 'assessment_cast' and fill data into it>
-- exec proc_InsertAssessmentCast
-- =============================================
CREATE PROCEDURE [dbo].[proc_InsertAssessmentCast] 


AS
BEGIN
      -- SET NOCOUNT ON added to prevent extra result sets from
      -- interfering with SELECT statements.
      SET NOCOUNT ON;

      DECLARE @tmpTableNames TABLE
      (
            TableName varchar(250),
            PatientID_ITM_ID INT,
            date_ITM_ID INT,
            KVSTableType INT,
            Association_ITM_ID INT
      )

      DECLARE @tmpAssociatedColumn_ITM_ID TABLE
      (
            InitialTableMasterID INT
      )

        DECLARE @AssociatedColumn_ITM_ID INT
        DECLARE @AssociatedColumn_ITM_ID_List VARCHAR(400)

        DECLARE @TableName varchar(250)
        DECLARE @PatientID_ITM_ID INT
        DECLARE @date_ITM_ID INT
        DECLARE @KVSTableType INT
        DECLARE @Association_ITM_ID INT
        DECLARE @SameRowID INT

        DECLARE @T04PKID INT
        DECLARE @T04CMID INT
        DECLARE @T04Value VARCHAR(250)

        DECLARE @sqlT04Value nvarchar(MAX)

        DECLARE @tmpValue TABLE
        (
            Value varchar(250)
        )


        CREATE TABLE #tmpAssessmentRows
        (
            PrimaryKeyTableID INT,
            ColumnID INT,
            Value varchar(250)
        )



      DECLARE @sqlSameRowID NVARCHAR(250),@sqlT04_Value_Query NVARCHAR(MAX)


       DECLARE @ColWithAliasTbl TABLE (colID int,colName varchar(50) )
       DECLARE @PivotTBL VARCHAR(MAX)=''
       DECLARE @ColID  VARCHAR(MAX) 
       DECLARE @ChkPtntID VARCHAR(MAX)
       DECLARE @ColName VARCHAR(MAX)
       DECLARE @AllColID VARCHAR(MAX) = ''
       DECLARE @AllColName VARCHAR(MAX) = ''


    BEGIN TRY

            IF EXISTS (SELECT name FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[tmpAssesessment_Cast]') AND type in (N'U'))
                BEGIN
                        DROP TABLE tmpAssesessment_Cast
                END

            IF EXISTS (SELECT name FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[assessment_cast]') AND type in (N'U'))
                BEGIN
                        DROP TABLE assessment_cast
                END

            IF NOT EXISTS (SELECT name FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[InitialOriginalDataKVS]') AND name = N'ix_InitialOriginalDataKVS_SameRowID')
                CREATE NONCLUSTERED INDEX [ix_InitialOriginalDataKVS_SameRowID] ON [dbo].[InitialOriginalDataKVS]
                (
                    [InitialTableMasterID] ASC
                )
                INCLUDE (   [SameRowID]) WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]


              --Insert Table names of tables having both columns: patientID and date
              INSERT INTO @tmpTableNames
              SELECT ITM1.TableName,ITM1.InitialTableMasterID,ITM2.InitialTableMasterID,ITM1.KVSTableType,0 AS Association_ITM_ID
              FROM InitialTableMaster ITM1 
              INNER JOIN InitialTableMaster ITM2 ON ITM1.TableName=ITM2.TableName
              WHERE ITM1.ColumnName ='patientID' AND  ITM2.ColumnName ='date' 

              --Set Association for the column in table 
              UPDATE @tmpTableNames
              SET Association_ITM_ID=Association
              FROM InitialTableMaster ITM
              INNER JOIN @tmpTableNames tmpTableNames ON tmpTableNames.TableName=ITM.TableName
              WHERE Association <> 0 AND tmpTableNames.KVSTableType=1

              --Do not consider tables with KVSTableType=1 having no Association
              DELETE FROM @tmpTableNames
              WHERE KVSTableType=1 AND Association_ITM_ID=0

                SELECT TOP 1
                            @PatientID_ITM_ID=PatientID_ITM_ID, 
                            @date_ITM_ID=date_ITM_ID,
                            @Association_ITM_ID=Association_ITM_ID

                FROM   @tmpTableNames

                    ----Logic to get the associated columns ID values in list
                    INSERT INTO @tmpAssociatedColumn_ITM_ID

                    SELECT InitialTableMasterID 
                    FROM InitialTableMaster 
                    WHERE Association=@Association_ITM_ID and InitialTableMasterID <>@Association_ITM_ID

                    WHILE ((SELECT COUNT(1) FROM @tmpAssociatedColumn_ITM_ID)>0)
                        BEGIN
                            SELECT TOP 1 @AssociatedColumn_ITM_ID=InitialTableMasterID
                            FROM @tmpAssociatedColumn_ITM_ID

                            SET @AssociatedColumn_ITM_ID_List= ISNULL(@AssociatedColumn_ITM_ID_List,'')  + '['+ CONVERT(NVARCHAR,@AssociatedColumn_ITM_ID) + '],'

                            DELETE FROM @tmpAssociatedColumn_ITM_ID
                            WHERE InitialTableMasterID=@AssociatedColumn_ITM_ID

                        END

                    SET @AssociatedColumn_ITM_ID_List=SUBSTRING(@AssociatedColumn_ITM_ID_List,0,LEN(@AssociatedColumn_ITM_ID_List))
                    print '1'
                    print @AssociatedColumn_ITM_ID_List

                    SET @sqlT04Value='      
                                            SELECT COALESCE('+ @AssociatedColumn_ITM_ID_List  + ') as ''Value''
                                            FROM [InitialOriginalDataKVS] 
                                            PIVOT(max(Value) 
                                            FOR InitialTableMasterID IN ('+ @AssociatedColumn_ITM_ID_List +')) AS PVTTable
                                            WHERE SameRowID = '


                    --DECLARE GetSameRowIDs CURSOR  STATIC LOCAL FOR
                    DECLARE GetSameRowIDs CURSOR  FORWARD_ONLY READ_ONLY FAST_FORWARD FOR
                    SELECT sameRowID FROM InitialOriginalDataKVS
                    WHERE InitialTableMasterID=@PatientID_ITM_ID AND NewFlag=1 
                    GROUP BY sameRowID

                    OPEN GetSameRowIDs
                    FETCH NEXT FROM GetSameRowIDs
                    INTO @SameRowID

                    WHILE (@@FETCH_STATUS = 0) -- Inner cursor loop
                    BEGIN
                                SET @T04PKID=0

                                SELECT @T04PKID=PrimaryKeyTableID 
                                FROM dbo.PrimaryKeyForPredicting
                                WHERE PatientID IN (SELECT value FROM dbo.InitialOriginalDataKVS  
                                                            WHERE SameRowID=@SameRowID AND InitialTableMasterID=@PatientID_ITM_ID) 
                                        AND [date] IN (SELECT value FROM dbo.InitialOriginalDataKVS  
                                                            WHERE SameRowID=@SameRowID AND InitialTableMasterID=@date_ITM_ID) 

                                --Process only if the combination of patientID and date exists in 'PrimaryKeyForPredicting' 
                                IF(ISNULL(@T04PKID,0)<> 0) 
                                    BEGIN
                                        DELETE FROM  @tmpValue

                                        SET @T04Value=NULL

                                        SET @sqlSameRowID=CONVERT(VARCHAR(50),@SameRowID)
                                        SET @sqlT04_Value_Query=@sqlT04Value+@sqlSameRowID

                                        INSERT INTO @tmpValue
                                        EXEC sp_executesql @sqlT04_Value_Query

                                        IF((SELECT COUNT(1) FROM @tmpValue)>0)
                                            BEGIN
                                                SELECT @T04Value=Value FROM @tmpValue
                                            END

                                        SELECT @T04CMID = ColumnID 
                                        FROM [dbo].[PrimaryKeyForModeling]
                                        WHERE ColumnName IN (SELECT value FROM [InitialOriginalDataKVS]
                                                            WHERE SameRowID=@SameRowID AND InitialTableMasterID=@Association_ITM_ID)

                                        IF(ISNULL(@T04CMID,0)<> 0) 
                                            BEGIN

                                                INSERT INTO #tmpAssessmentRows
                                                (PrimaryKeyTableID,ColumnID,Value)
                                                VALUES(@T04PKID,@T04CMID,@T04Value)
                                            END
                                    END

                        FETCH NEXT FROM GetSameRowIDs
                        INTO @SameRowID
                    END  
                    CLOSE GetSameRowIDs
                    DEALLOCATE GetSameRowIDs

                    SELECT PKP.PatientID,PKP.[Date],ColumnID,Value into tmpAssesessment_Cast
                    FROM #tmpAssessmentRows AR 
                    INNER JOIN dbo.PrimaryKeyForPredicting PKP ON AR.PrimaryKeyTableID=PKP.PrimaryKeyTableID
                    order by PKP.PrimaryKeyTableID

                    -----------------------------
                    --Logic for assesment_cast table creation from the data in rows
                    ------------------------------

                    INSERT INTO  @ColWithAliasTbl 
                    SELECT ColumnID,[ColumnName] 
                    FROM [dbo].[PrimaryKeyForModeling]
                    WHERE ColumnID IN (SELECT Distinct ColumnID FROM tmpAssesessment_Cast)

                    While EXISTS (SELECT colID,colName FROM @ColWithAliasTbl)
                                  Begin
                                    SELECT @ColID='['+CONVERT(VARCHAR,min(colID))+'],' FROM @ColWithAliasTbl
                                    SELECT @ColName='['+CONVERT(VARCHAR,colID)+'] AS '''+ colName+''',' FROM @ColWithAliasTbl WHERE colID = (SELECT min(colID) FROM @ColWithAliasTbl)

                                    SET @AllColID = @AllColID+@ColID
                                    SET @AllColName = @AllColName+@ColName

                                    DELETE from @ColWithAliasTbl Where colID = (SELECT min(colID) FROM @ColWithAliasTbl)
                                  End
                                  print @AllColID
                                  print LEN(@AllColID)
                                  SET @AllColID = SUBSTRING(@AllColID, 1, LEN(@AllColID)-1)
                                  print '2'
                                  SET @AllColName = SUBSTRING(@AllColName, 1, LEN(@AllColName)-1)
                                  print '3'


                                  SET @PivotTBL = 'SELECT patientID, [date], '+@AllColName + 
                                  ' into assessment_cast FROM  (SELECT * FROM [dbo].[tmpAssesessment_Cast])  KVS
                                         PIVOT (Max(Value) FOR [ColumnID] IN ('+@AllColID+') ) pvt order by 1'

                    EXEC(@PivotTBL) 

                    --Drop temporary table 
                    IF OBJECT_ID('dbo.tmpAssesessment_Cast', 'U') IS NOT NULL 
                        DROP TABLE dbo.tmpAssesessment_Cast;

                    DROP TABLE #tmpAssessmentRows

                    --Return the assessment_cast table data
                    SELECT * FROM assessment_cast

    END TRY
    BEGIN CATCH
            -- Raise an error with the details of the exception
            DECLARE @ErrMsg nvarchar(4000), @ErrSeverity INT,@ErrorState INT

            SELECT @ErrSeverity=ERROR_SEVERITY(),
                        @ErrMsg= ERROR_MESSAGE(),
                        @ErrorState=ERROR_STATE();

            RAISERROR(@ErrMsg, @ErrSeverity, @ErrorState)
            EXEC sp_addmessage 50005,@ErrSeverity,@ErrMsg,'us_english', 'with_log'
    END CATCH
END

GO

0 个答案:

没有答案