Преобразуйте хранимую процедуру SQL Server в Oracle - PullRequest
0 голосов
/ 17 января 2011

Я преобразовал следующий SP (SQL Server) в Oracle. Это не компилируется. Любые предложения ?????

ALTER PROCEDURE [dbo].[Calendar_GetByDate]
(
   @DueDate datetime,
   @StaffId int,
   @IsForMonth bit,
   @SubpoennaString nvarchar(max),
   @ActivityString nvarchar(max),
   @TrainingString nvarchar(max),
   @RequestString nvarchar(max),
   @OtherString nvarchar(max),
   @CaseOffenseString nvarchar(max),
   @CaseIndividualString nvarchar(max),
   @CaseInvestigationString nvarchar(max),
   @CommunicationLogString nvarchar(max),
   @CrimeSceneString nvarchar(max),
   @CalenderDisplayList nvarchar(100),
   @CalenderCaseId nvarchar(max)=null
)

AS 
BEGIN
    BEGIN TRY
    Declare @dateStr as nvarchar(100)
--select @IsForMonth
    If @IsForMonth = 1
        Begin
            SET @dateStr = 'month'
        END
    ELSE
        BEGIN
            SET @dateStr = 'day'
        END

    DECLARE @str AS nvarchar(max)   
    SET @str = '
                (SELECT [Calendar].[CalendarId], [Calendar].[EntityTypeId],
                  [Calendar].[EntityId], [Calendar].[StaffId], [Calendar].[CaseId],
                  [Calendar].[DueDate], [Calendar].[IsActive], [Calendar].[IsCaseCalendar],
                  [Calendar].[LastUpdatedBy], [Calendar].[LastUpdateDate] ,  cast(' + @SubpoennaString + ' as nvarchar(max)) AS Description
                FROM [Calendar]  WITH (NOLOCK)
                LEFT JOIN SubPoena_Master WITH (NOLOCK) ON [Calendar].EntityId = SubPoena_Master.SPID
                Inner JOIN dbo.fnSplit(''' + @CalenderDisplayList + ''', '','') as FN on FN.ItemValue = [Calendar].EntityTypeId
                WHERE ([Calendar].EntityTypeId = 3 AND datediff(' + @dateStr + ',[Calendar].[DueDate],''' + cast(@DueDate as nvarchar(20)) + ''') = 0 AND [StaffId] = ' + cast(@StaffId as nvarchar(10)) + '))
            UNION
                (SELECT [Calendar].[CalendarId], [Calendar].[EntityTypeId],
                  [Calendar].[EntityId], [Calendar].[StaffId], [Calendar].[CaseId],
                  [Calendar].[DueDate], [Calendar].[IsActive], [Calendar].[IsCaseCalendar],
                  [Calendar].[LastUpdatedBy], [Calendar].[LastUpdateDate] ,  cast(' + @ActivityString + ' as nvarchar(max)) AS Description
                FROM [Calendar]  WITH (NOLOCK)
                LEFT JOIN Activity WITH (NOLOCK) ON [Calendar].EntityId = Activity.ActivityId
                Inner JOIN dbo.fnSplit(''' + @CalenderDisplayList + ''', '','') as FN on FN.ItemValue = [Calendar].EntityTypeId
                WHERE ([Calendar].EntityTypeId = 4 AND datediff(' + @dateStr + ',[Calendar].[DueDate],''' + cast(@DueDate as nvarchar(20)) + ''') = 0 AND [StaffId] = ' + cast(@StaffId as nvarchar(10)) + '))
            UNION
                (SELECT [Calendar].[CalendarId], [Calendar].[EntityTypeId],
                  [Calendar].[EntityId], [Calendar].[StaffId], [Calendar].[CaseId],
                  [Calendar].[DueDate], [Calendar].[IsActive], [Calendar].[IsCaseCalendar],
                  [Calendar].[LastUpdatedBy], [Calendar].[LastUpdateDate] ,  cast(' + @CaseOffenseString + ' as nvarchar(max)) AS Description
                FROM [Calendar] WITH (NOLOCK) 
                LEFT JOIN CaseOffense WITH (NOLOCK) ON CaseOffense.CaseOffId = [Calendar].EntityId
                Inner JOIN dbo.fnSplit(''' + @CalenderDisplayList + ''', '','') as FN on FN.ItemValue = [Calendar].EntityTypeId
                WHERE ([Calendar].EntityTypeId = 5 AND datediff(' + @dateStr + ',[Calendar].[DueDate],''' + cast(@DueDate as nvarchar(20)) + ''') = 0 AND [StaffId] = ' + cast(@StaffId as nvarchar(10)) + ')'

            IF NOT @CalenderCaseId IS NULL
            BEGIN
                SET @str = @str + ' AND [Calendar].CaseId = ''' + @CalenderCaseId + ''''
            END


            SET @str = @str + ')
            UNION
                (SELECT [Calendar].[CalendarId], [Calendar].[EntityTypeId],
                  [Calendar].[EntityId], [Calendar].[StaffId], [Calendar].[CaseId],
                  [Calendar].[DueDate], [Calendar].[IsActive], [Calendar].[IsCaseCalendar],
                  [Calendar].[LastUpdatedBy], [Calendar].[LastUpdateDate] , cast(' + @CaseIndividualString + ' as nvarchar(max)) AS Description
                FROM [Calendar] WITH (NOLOCK) 
                LEFT JOIN IndividualMaster WITH (NOLOCK) ON IndividualMaster.IndividualId = [Calendar].EntityId
                Inner JOIN dbo.fnSplit(''' + @CalenderDisplayList + ''', '','') as FN on FN.ItemValue = [Calendar].EntityTypeId
                WHERE ([Calendar].EntityTypeId = 6 AND datediff(' + @dateStr + ',[Calendar].[DueDate],''' + cast(@DueDate as nvarchar(20)) + ''') = 0 AND [StaffId] = ' + cast(@StaffId as nvarchar(10)) + ')'

            IF NOT @CalenderCaseId IS NULL
            BEGIN
                SET @str = @str + ' AND [Calendar].CaseId = ''' + @CalenderCaseId + ''''
            END


            SET @str = @str + ')
            UNION
                (SELECT [Calendar].[CalendarId], [Calendar].[EntityTypeId],
                  [Calendar].[EntityId], [Calendar].[StaffId], [Calendar].[CaseId],
                  [Calendar].[DueDate], [Calendar].[IsActive], [Calendar].[IsCaseCalendar],
                  [Calendar].[LastUpdatedBy], [Calendar].[LastUpdateDate] ,  cast(' + @CaseInvestigationString + ' as nvarchar(max)) AS Description
                FROM [Calendar] WITH (NOLOCK) 
                LEFT JOIN CaseInvestigation WITH (NOLOCK) ON [Calendar].EntityId = CaseInvestigation.InvestigationId
                Inner JOIN dbo.fnSplit(''' + @CalenderDisplayList + ''', '','') as FN on FN.ItemValue = [Calendar].EntityTypeId
                WHERE ([Calendar].EntityTypeId = 7 AND datediff(' + @dateStr + ',[Calendar].[DueDate],''' + cast(@DueDate as nvarchar(20)) + ''') = 0 AND [StaffId] = ' + cast(@StaffId as nvarchar(10)) + ')'

            IF NOT @CalenderCaseId IS NULL
            BEGIN
                SET @str = @str + ' AND [Calendar].CaseId = ''' + @CalenderCaseId + ''''
            END


            SET @str = @str + ')
            UNION
                (SELECT [Calendar].[CalendarId], [Calendar].[EntityTypeId],
                  [Calendar].[EntityId], [Calendar].[StaffId], [Calendar].[CaseId],
                  [Calendar].[DueDate], [Calendar].[IsActive], [Calendar].[IsCaseCalendar],
                  [Calendar].[LastUpdatedBy], [Calendar].[LastUpdateDate] ,  cast(' + @CommunicationLogString + ' as nvarchar(max)) AS Description
                FROM [Calendar] WITH (NOLOCK) 
                LEFT JOIN CommunicationLog WITH (NOLOCK) ON [Calendar].EntityId = CommunicationLog.LogId
                Inner JOIN dbo.fnSplit(''' + @CalenderDisplayList + ''', '','') as FN on FN.ItemValue = [Calendar].EntityTypeId
                WHERE ([Calendar].EntityTypeId = 8 AND datediff(' + @dateStr + ',[Calendar].[DueDate],''' + cast(@DueDate as nvarchar(20)) + ''') = 0 AND [StaffId] = ' + cast(@StaffId as nvarchar(10)) + ')'
            IF NOT @CalenderCaseId IS NULL
            BEGIN
                SET @str = @str + ' AND [Calendar].CaseId = ''' + @CalenderCaseId + ''''
            END


            SET @str = @str + ')
            UNION
                (SELECT [Calendar].[CalendarId], [Calendar].[EntityTypeId],
                  [Calendar].[EntityId], [Calendar].[StaffId], [Calendar].[CaseId],
                  [Calendar].[DueDate], [Calendar].[IsActive], [Calendar].[IsCaseCalendar],
                  [Calendar].[LastUpdatedBy], [Calendar].[LastUpdateDate] ,  cast(' + @CrimeSceneString + ' as nvarchar(max)) AS Description
                FROM [Calendar]  WITH (NOLOCK)
                LEFT JOIN Scene WITH (NOLOCK) ON [Calendar].EntityId = Scene.CrimeSceneId
                Inner JOIN dbo.fnSplit(''' + @CalenderDisplayList + ''', '','') as FN on FN.ItemValue = [Calendar].EntityTypeId
                WHERE ([Calendar].EntityTypeId = 9 AND datediff(' + @dateStr + ',[Calendar].[DueDate],''' + cast(@DueDate as nvarchar(20)) + ''') = 0 AND [StaffId] = ' + cast(@StaffId as nvarchar(10)) + ')'

            IF NOT @CalenderCaseId IS NULL
            BEGIN
                SET @str = @str + ' AND [Calendar].CaseId = ''' + @CalenderCaseId + ''''
            END

            SET @str = @str + ')


ORDER BY [Calendar].[DueDate]
'
--select @str   
exec (@str)

    END TRY

    BEGIN CATCH
        SELECT  ERROR_MESSAGE() as ErrorMessage;
    END CATCH


    RETURN 
END

Хранимый процесс для ORACLE

CREATE OR REPLACE PROCEDURE ADMIN.Calendar_GetByDate(DueDate IN TIMESTAMP,
   StaffId IN NUMBER,
   IsForMonth IN NUMBER,
   SubpoennaString IN nvarchar2,
   ActivityString IN nvarchar2,
   TrainingString IN nvarchar2,
   RequestString IN nvarchar2,
   OtherString IN nvarchar2,
   CaseOffenseString IN nvarchar2,
   CaseIndividualString IN nvarchar2,
   CaseInvestigationString IN nvarchar2,
   CommunicationLogString IN nvarchar2,
   CrimeSceneString IN nvarchar2,
   CalenderDisplayList IN NVARCHAR2,
   CalenderCaseId IN nvarchar2 DEFAULT null, v_refcur OUT SYS_REFCURSOR)

   as
   dateStr  NVARCHAR2(100);
   str  nvarchar2(32000);

   SWV_VarStr varchar2(32000);
   str1 varchar2(32000);
BEGIN
   BEGIN
      If IsForMonth = 1 then

         dateStr := 'month';
      ELSE
         dateStr := 'day';
      end if;
      str := ' SELECT [Calendar].[CalendarId], [Calendar].[EntityTypeId],
                  [Calendar].[EntityId], [Calendar].[StaffId], [Calendar].[CaseId],
                  [Calendar].[DueDate], [Calendar].[IsActive], [Calendar].[IsCaseCalendar],
                  [Calendar].[LastUpdatedBy], [Calendar].[LastUpdateDate] ,  cast(' || SubpoennaString || ' as nvarchar2(4000)) AS Description
                FROM [Calendar]  WITH (NOLOCK)
                LEFT JOIN SubPoena_Master WITH (NOLOCK) ON [Calendar].EntityId = SubPoena_Master.SPID
                Inner JOIN dbo.fnSplit(''' || CalenderDisplayList || ''', '','') as FN on FN.ItemValue = [Calendar].EntityTypeId
                WHERE ([Calendar].EntityTypeId = 3 AND datediff(' || dateStr || ',[Calendar].[DueDate],''' || SUBSTR(cast(DueDate as NVARCHAR2),1,20) || ''') = 0 AND StaffId = ' || SUBSTR(cast(StaffId as NVARCHAR2),1,10) || '))     UNION   (SELECT [Calendar].[CalendarId], [Calendar].[EntityTypeId],
                  [Calendar].[EntityId], [Calendar].[StaffId], [Calendar].[CaseId],
                  [Calendar].[DueDate], [Calendar].[IsActive], [Calendar].[IsCaseCalendar],
                  [Calendar].[LastUpdatedBy], [Calendar].[LastUpdateDate] ,  cast(' || ActivityString || 'as nvarchar2(4000)) AS Description
                FROM [Calendar]  WITH (NOLOCK)
                LEFT JOIN Activity WITH (NOLOCK) ON [Calendar].EntityId = Activity.ActivityId
                Inner JOIN dbo.fnSplit(''' || CalenderDisplayList || ''','','') AS FN on FN.ItemValue = [Calendar].EntityTypeId
                WHERE ([Calendar].EntityTypeId = 4 AND datediff(' || dateStr || ',[Calendar].[DueDate],''' || SUBSTR(cast(DueDate as NVARCHAR2),1,20) || ''') = 0 AND StaffId = ' || SUBSTR(cast(StaffId as NVARCHAR2),1,10) || '))     UNION   (SELECT [Calendar].[CalendarId], [Calendar].[EntityTypeId],
                  [Calendar].[EntityId], [Calendar].[StaffId], [Calendar].[CaseId],
                  [Calendar].[DueDate], [Calendar].[IsActive], [Calendar].[IsCaseCalendar],
                  [Calendar].[LastUpdatedBy], [Calendar].[LastUpdateDate] ,  cast(' || CaseOffenseString || 'as nvarchar2(4000)) AS Description
                FROM [Calendar] WITH (NOLOCK) 
                LEFT JOIN CaseOffense WITH (NOLOCK) ON CaseOffense.CaseOffId = [Calendar].EntityId
                Inner JOIN dbo.fnSplit(''' || CalenderDisplayList || ''','','') AS FN on FN.ItemValue = [Calendar].EntityTypeId
                WHERE ([Calendar].EntityTypeId = 5 AND datediff(' || dateStr || ',[Calendar].[DueDate],''' || SUBSTR(cast(DueDate as NVARCHAR2),1,20) || ''') = 0 AND StaffId = ' || SUBSTR(cast(StaffId as NVARCHAR2),1,10) || ')';
      IF NOT CalenderCaseId IS NULL then

         str := str || ' AND [Calendar].CaseId =  ''' || CalenderCaseId || '''';
      end if;
      str := str || 'UNION  (SELECT [Calendar].[CalendarId], [Calendar].[EntityTypeId],
                  [Calendar].[EntityId], [Calendar].[StaffId], [Calendar].[CaseId],
                  [Calendar].[DueDate], [Calendar].[IsActive], [Calendar].[IsCaseCalendar],
                  [Calendar].[LastUpdatedBy], [Calendar].[LastUpdateDate] , cast(' || CaseIndividualString || 'as nvarchar2(4000)) AS Description
                FROM [Calendar] WITH (NOLOCK) 
                LEFT JOIN IndividualMaster WITH (NOLOCK) ON IndividualMaster.IndividualId = [Calendar].EntityId
                Inner JOIN dbo.fnSplit(''' || CalenderDisplayList || ''','','') AS FN on FN.ItemValue = [Calendar].EntityTypeId
                WHERE ([Calendar].EntityTypeId = 6 AND datediff(' || dateStr || '[Calendar].[DueDate],''' || SUBSTR(cast(DueDate as NVARCHAR2),1,20) || ''') = 0 AND StaffId = ' || SUBSTR(cast(StaffId as NVARCHAR2),1,10) || ')';
      IF NOT CalenderCaseId IS NULL then

         str := str || ' AND [Calendar].CaseId = ''' || CalenderCaseId || '''';
      end if;
      str := str || 'UNION  (SELECT [Calendar].[CalendarId], [Calendar].[EntityTypeId],
                  [Calendar].[EntityId], [Calendar].[StaffId], [Calendar].[CaseId],
                  [Calendar].[DueDate], [Calendar].[IsActive], [Calendar].[IsCaseCalendar],
                  [Calendar].[LastUpdatedBy], [Calendar].[LastUpdateDate] ,  cast(' || CaseInvestigationString || ' as nvarchar2(4000)) AS Description
                FROM [Calendar] WITH (NOLOCK) 
                LEFT JOIN CaseInvestigation WITH (NOLOCK) ON [Calendar].EntityId = CaseInvestigation.InvestigationId
                Inner JOIN dbo.fnSplit(''' || CalenderDisplayList || ''','','') AS FN on FN.ItemValue = [Calendar].EntityTypeId
                WHERE ([Calendar].EntityTypeId = 7 AND datediff(' || dateStr || ',[Calendar].[DueDate],''' || SUBSTR(cast(DueDate as NVARCHAR2),1,20) || ''') = 0 AND [StaffId] = ' || SUBSTR(cast(StaffId as NVARCHAR2),1,10) || ')';
      IF NOT CalenderCaseId IS NULL then

         str := str || ' AND [Calendar].CaseId = ''' || CalenderCaseId || '''';
      end if;
      str1 :=  'UNION   (SELECT [Calendar].[CalendarId], [Calendar].[EntityTypeId],
                  [Calendar].[EntityId], [Calendar].[StaffId], [Calendar].[CaseId],
                  [Calendar].[DueDate], [Calendar].[IsActive], [Calendar].[IsCaseCalendar],
                  [Calendar].[LastUpdatedBy], [Calendar].[LastUpdateDate] ,  cast(' || CommunicationLogString || ' as nvarchar2(4000)) AS Description
                FROM [Calendar] WITH (NOLOCK) 
                LEFT JOIN CommunicationLog WITH (NOLOCK) ON [Calendar].EntityId = CommunicationLog.LogId
                Inner JOIN dbo.fnSplit(''' || CalenderDisplayList || ''','','') AS FN on FN.ItemValue = [Calendar].EntityTypeId
                WHERE ([Calendar].EntityTypeId = 8 AND datediff(' || dateStr || ',[Calendar].[DueDate],''' || SUBSTR(cast(DueDate as NVARCHAR2),1,20) || ''') = 0 AND [StaffId] = ' || SUBSTR(cast(StaffId as NVARCHAR2),1,10) || ')';
      IF NOT CalenderCaseId IS NULL then

         str1 := str1 || ' AND [Calendar].CaseId = ''' || CalenderCaseId || '''';
      end if;
      str1 := str1 || 'UNION    (SELECT [Calendar].[CalendarId], [Calendar].[EntityTypeId],
                  [Calendar].[EntityId], [Calendar].[StaffId], [Calendar].[CaseId],
                  [Calendar].[DueDate], [Calendar].[IsActive], [Calendar].[IsCaseCalendar],
                  [Calendar].[LastUpdatedBy], [Calendar].[LastUpdateDate] ,  cast(' || CrimeSceneString || ' as nvarchar2(4000)) AS Description
                FROM [Calendar]  WITH (NOLOCK)
                LEFT JOIN Scene WITH (NOLOCK) ON [Calendar].EntityId = Scene.CrimeSceneId
                Inner JOIN dbo.fnSplit(''' || CalenderDisplayList || ''','','') AS FN on FN.ItemValue = [Calendar].EntityTypeId
                WHERE ([Calendar].EntityTypeId = 9 AND datediff(' || dateStr || ',[Calendar].[DueDate],''' || SUBSTR(cast(DueDate as NVARCHAR2),1,20) || ''') = 0 AND [StaffId] = ' || SUBSTR(cast(StaffId as NVARCHAR2),1,10) || ')';
      IF NOT CalenderCaseId IS NULL then

         str1 := str1 || ' AND [Calendar].CaseId = ''' || CalenderCaseId || '''';
      end if;
      str1 := str1 || ') ORDER BY [Calendar].[DueDate]';
--select @str   
      SWV_VarStr := str || str1;
      EXECUTE IMMEDIATE SWV_VarStr;


   END;


   RETURN; 
END;
/

Ответы [ 2 ]

3 голосов
/ 17 января 2011

Вы не преобразовали SQL в Oracle:

  • Нет такой функции, как DATEDIFF в Oracle
  • WITH (NOLOCK) недопустимо в Oracle
  • [TableName]. Синтаксис [ColumnName] недопустим в Oracle
2 голосов
/ 17 января 2011

Если вы хотите перенести TSQL в Oracle, я советую вам сначала переписать свой код SQL наиболее удобным для Orcale способом.

Первое наблюдение состоит в том, что вы объявляете все строковые параметры как varchar (max). Что бы вы сделали, если ваш код должен работать на SQL-Server-2005. Вы бы выбрали varchar (8000), nvarchar (4000), текст или ntext?

Будет ли приемлемым varchar (4000) или nvarchar (4000)?

Это не вопрос длины, а вопрос о типах данных. Вам нужны ужасные параметры CLOB или вы можете использовать хороший varchar2?

Хорошие новости: Oracle не заботится о длине параметров varchar2. Вы не играете в игру. Мы просто увеличили размер столбца column_x на 10 (мы не хотим тратить хранилище), и теперь вы можете настроить эти 10 хранимых процедур, используя столбец.

Секунда Лучше уберите все квадратные скобки [] из вашего TSQL, если вы зависите от них, у вас наверняка будут некоторые проблемы при переходе на Oracle.

Третий Спросите себя время дерева, если вы действительно хотите использовать динамический sql. После короткого взгляда на ваш код, я думаю, я бы попытался переписать его как прямой TSQ, возможно, используя некоторую логику if else. Вы, наверное, спросите почему. Ответ ради производительности. Я упоминаю только ключевые слова: переменные связывания, контекст, общий пул. Oracle имеет ограниченный ресурс, называемый общим пулом, который становится узким местом, когда вы легко и просто переносите динамический sql с sql-сервера. Поверьте мне, лучше настроить свой SQL, чтобы не использовать динамический SQL, чем заботиться об особых потребностях Oracle.

Далее Используйте конструкции, которые похожи в обеих системах

  • аналитические функции
  • общие табличные выражения (называемые в документации Oracle факторингом подзапроса)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...