Хранимая процедура SQL Server во встроенном SQL с переменными хоста - PullRequest
0 голосов
/ 19 октября 2018

В MicroFocus Cobol я создаю хранимую процедуру с использованием переменных хоста.Код SQL выглядит следующим образом:

 CREATE PROCEDURE dbo.LLPSY_PK1_BPS_PROC_INDEX  
 AS 
 BEGIN 
     IF EXISTS (SELECT * FROM sysobjects 
                WHERE id = object_id(N'LLPSY_PK1_BPS_INDEX ') 
                  AND OBJECTPROPERTY(id, N'IsTable') = 1) 
        DROP TABLE LLPSY_PK1_BPS_INDEX 

     IF EXISTS (SELECT * FROM sysobjects 
                WHERE id = object_id(N'LLPSY_PK1_BPS_INDEX_1    ') 
                  AND OBJECTPROPERTY(id, N'IsTable') = 1) 
        DROP TABLE LLPSY_PK1_BPS_INDEX_1    

     IF EXISTS (SELECT * FROM sysobjects 
                WHERE id = object_id(N'LLPSY_PK1_BPS_INDEX_2    ') 
                  AND OBJECTPROPERTY(id, N'IsTable') = 1) 
        DROP TABLE LLPSY_PK1_BPS_INDEX_2    

     SELECT 
         PAYMENT_REF = CASE C.ACNT_TYPE WHEN 1 THEN  CAST(SUBSTRING(A.TREFERENCE,CAST(01 AS int),CAST(30 AS int)) AS NCHAR(30))WHEN 0 THEN  CAST(SUBSTRING(A.TREFERENCE,CAST(01 AS int),CAST(30 AS int)) AS NCHAR(30))WHEN 2 THEN  CAST(SUBSTRING(A.TREFERENCE,CAST(01 AS int),CAST(30 AS int)) AS NCHAR(30))WHEN 4 THEN  CAST(SUBSTRING(A.TREFERENCE,CAST(01 AS int),CAST(30 AS int)) AS NCHAR(30))END ,A.ACCNT_CODE AS ACCOUNT,BANKNO=CASE WHEN E.BANK_ACNT_NUM IS NULL THEN''ELSE E.BANK_ACNT_NUM END,AMOUNT=CASE WHEN A.AMOUNT>0 THEN A.AMOUNT ELSE A.AMOUNT*-1 END,A.D_C AS AMOUNT_DC,OTHER_AMOUNT=CASE WHEN A.OTHER_AMT>0 THEN A.OTHER_AMT ELSE A.OTHER_AMT*-1 END,A.D_C AS OTHER_AMOUNT_DC,CAST(A.ACCNT_CODE AS NCHAR(15))+CAST(A.PERIOD AS NCHAR(07))+CONVERT(CHAR(16),A.TRANS_DATETIME,112)AS LEDGER_KEY,CAST(A.JRNAL_NO AS NUMERIC(09))AS JN,CAST(A.JRNAL_LINE AS NUMERIC(09))AS TN,'A'AS BUDGET,' 'AS LOCAL_CURR,' 'AS COUNT,0 AS COUNTS,CAST(' 'AS NCHAR(80))AS TNS,C.DESCR AS ACCOUNT_NAME,A.DESCRIPTN AS DESCRIPTION,A.CONV_CODE,A.TREFERENCE AS TRANS_REF,' 'AS MATCHED,C.ACNT_TYPE AS AT,' 'AS DOUBLES,' 'AS SPLIT,ADD_1=E.A,' 'AS ADD_2,' 'AS ADD_3,PAYMENT_ADD=' ' INTO LLPSY_PK1_BPS_INDEX_1    FROM PK1_A_SALFLDG AS A INNER JOIN PK1_ACNT AS C ON A.ACCNT_CODE=C.ACNT_CODE LEFT JOIN LLPSY_PK1_BNK_BKA_VIEW   AS E ON A.ACCNT_CODE=E.ACCOUNT AND E.A<>'M'  OR  A.ACCNT_CODE=E.ACCOUNT AND E.A= 'M'  AND A.ANAL_T9   =E.BDS       LEFT JOIN PK1_A_SALFLDG_LAD  AS M ON A.ACCNT_CODE=M.ACCNT_CODE AND A.JRNAL_NO=M.JRNAL_NO AND A.JRNAL_LINE=M.JRNAL_LINE WHERE(( A.ACCNT_CODE BETWEEN ? and ? AND C.ACNT_TYPE IN(1)))AND ALLOCATION NOT IN ('A','P','Y','C','R','2','W') UNION SELECT PAYMENT_REF=CASE C.ACNT_TYPE WHEN 1 THEN  CAST(SUBSTRING(A.TREFERENCE,CAST(01 AS int),CAST(30 AS int)) AS NCHAR(30))WHEN 0 THEN  CAST(SUBSTRING(A.TREFERENCE,CAST(01 AS int),CAST(30 AS int)) AS NCHAR(30))WHEN 2 THEN  CAST(SUBSTRING(A.TREFERENCE,CAST(01 AS int),CAST(30 AS int)) AS NCHAR(30))WHEN 4 THEN  CAST(SUBSTRING(A.TREFERENCE,CAST(01 AS int),CAST(30 AS int)) AS NCHAR(30))END ,A.ACCNT_CODE AS ACCOUNT,BANKNO=CASE WHEN E.BANK_ACNT_NUM IS NULL THEN''ELSE E.BANK_ACNT_NUM END,AMOUNT=CASE WHEN A.AMOUNT>0 THEN A.AMOUNT ELSE A.AMOUNT*-1 END,A.D_C AS AMOUNT_DC,OTHER_AMOUNT=CASE WHEN A.OTHER_AMT>0 THEN A.OTHER_AMT ELSE A.OTHER_AMT*-1 END,A.D_C AS OTHER_AMOUNT_DC,CAST(A.ACCNT_CODE AS NCHAR(15))+CAST(A.PERIOD AS NCHAR(07))+CONVERT(CHAR(16),A.TRANS_DATETIME,112)AS LEDGER_KEY,CAST(A.JRNAL_NO AS NUMERIC(09))AS JN,CAST(A.JRNAL_LINE AS NUMERIC(09))AS TN,'B'AS BUDGET,' 'AS LOCAL_CURR,' 'AS COUNT,0 AS COUNTS,CAST(' 'AS NCHAR(80))AS TNS,C.DESCR AS ACCOUNT_NAME,A.DESCRIPTN AS DESCRIPTION,A.CONV_CODE,A.TREFERENCE AS TRANS_REF,' 'AS MATCHED,C.ACNT_TYPE AS AT,' 'AS DOUBLES,' 'AS SPLIT,ADD_1=E.A,' 'AS ADD_2,' 'AS ADD_3,PAYMENT_ADD=' '                               FROM PK1_B_SALFLDG AS A INNER JOIN PK1_ACNT AS C ON A.ACCNT_CODE=C.ACNT_CODE LEFT JOIN LLPSY_PK1_BNK_BKA_VIEW   AS E ON A.ACCNT_CODE=E.ACCOUNT AND E.A<>'M'  OR  A.ACCNT_CODE=E.ACCOUNT AND E.A= 'M'  AND A.ANAL_T9   =E.BDS       LEFT JOIN PK1_A_SALFLDG_LAD  AS M ON A.ACCNT_CODE=M.ACCNT_CODE AND A.JRNAL_NO=M.JRNAL_NO AND A.JRNAL_LINE=M.JRNAL_LINE WHERE(( A.ACCNT_CODE BETWEEN ? and ? AND C.ACNT_TYPE IN(1)))AND ALLOCATION NOT IN ('A','P','Y','C','R','2','W')SELECT PAYMENT_REF,ACCOUNT,BANKNO,AMOUNT,AMOUNT_DC,OTHER_AMOUNT,OTHER_AMOUNT_DC,LEDGER_KEY,JN,TN,BUDGET,LOCAL_CURR,COUNT,COUNTS,TNS,ACCOUNT_NAME,DESCRIPTION,CONV_CODE,TRANS_REF,MATCHED,AT,REC_KEY=IDENTITY(int,1,1),DOUBLES,SPLIT,ADD_1,ADD_2,ADD_3,PAYMENT_ADD INTO LLPSY_PK1_BPS_INDEX_2     FROM LLPSY_PK1_BPS_INDEX_1   SELECT PAYMENT_REF,ACCOUNT,BANKNO,AMOUNT,AMOUNT_DC,OTHER_AMOUNT,OTHER_AMOUNT_DC,LEDGER_KEY,JN,TN,BUDGET,LOCAL_CURR,COUNT,COUNTS,TNS,ACCOUNT_NAME,DESCRIPTION,CONV_CODE,TRANS_REF,MATCHED,AT,REC_KEY,DOUBLES,SPLIT,ADD_1,ADD_2,ADD_3 INTO dbo.LLPSY_PK1_BPS_INDEX  FROM LLPSY_PK1_BPS_INDEX_2    WHERE ISNUMERIC(LTRIM(PAYMENT_REF))=1   SET IDENTITY_INSERT LLPSY_PK1_BPS_INDEX  ON  INSERT INTO LLPSY_PK1_BPS_INDEX  (PAYMENT_REF,ACCOUNT,BANKNO,AMOUNT,AMOUNT_DC,OTHER_AMOUNT,OTHER_AMOUNT_DC,LEDGER_KEY,JN,TN,BUDGET,LOCAL_CURR,COUNT,COUNTS,TNS,ACCOUNT_NAME,DESCRIPTION,CONV_CODE,TRANS_REF,MATCHED,AT,REC_KEY,DOUBLES,SPLIT,ADD_1,ADD_2,ADD_3) SELECT dbo.LLPSY_Remove_AB_String(PAYMENT_REF), ACCOUNT,BANKNO,AMOUNT,AMOUNT_DC,OTHER_AMOUNT,OTHER_AMOUNT_DC,LEDGER_KEY,JN,TN,BUDGET,LOCAL_CURR,COUNT,COUNTS,TNS,ACCOUNT_NAME,DESCRIPTION,CONV_CODE,TRANS_REF,MATCHED,AT,REC_KEY,DOUBLES,SPLIT,ADD_1,ADD_2,ADD_3 FROM LLPSY_PK1_BPS_INDEX_2    WHERE dbo.LLPSY_Remove_AB_String(PAYMENT_REF)<>'' AND  dbo.LLPSY_Remove_AB_String(PAYMENT_REF)<>PAYMENT_REF
  SET IDENTITY_INSERT LLPSY_PK1_BPS_INDEX  ON  INSERT INTO LLPSY_PK1_BPS_INDEX  (PAYMENT_REF,ACCOUNT,BANKNO,AMOUNT,AMOUNT_DC,OTHER_AMOUNT,OTHER_AMOUNT_DC,LEDGER_KEY,JN,TN,BUDGET,LOCAL_CURR,COUNT,COUNTS,TNS,ACCOUNT_NAME,DESCRIPTION,CONV_CODE,TRANS_REF,MATCHED,AT,REC_KEY,DOUBLES,SPLIT,ADD_1,ADD_2,ADD_3) SELECT dbo.LLPSY_Remove_AB_String(PAYMENT_ADD)AS PAYMENT_REF, ACCOUNT,BANKNO,AMOUNT,AMOUNT_DC,OTHER_AMOUNT,OTHER_AMOUNT_DC,LEDGER_KEY,JN,TN,BUDGET,LOCAL_CURR,COUNT,COUNTS,TNS,ACCOUNT_NAME,DESCRIPTION,CONV_CODE,TRANS_REF,MATCHED,AT,REC_KEY,DOUBLES,SPLIT,ADD_1,ADD_2,ADD_3 FROM LLPSY_PK1_BPS_INDEX_2    WHERE PAYMENT_ADD IS NOT NULL AND PAYMENT_ADD<>'' AND dbo.LLPSY_Remove_AB_String(PAYMENT_ADD)<>'' CREATE INDEX PAYMENT_REF_IND ON LLPSY_PK1_BPS_INDEX  (PAYMENT_REF)  CREATE INDEX BANKNO_IND ON LLPSY_PK1_BPS_INDEX  (BANKNO)  CREATE INDEX LEDGER_KEY_IND ON LLPSY_PK1_BPS_INDEX  (LEDGER_KEY)  CREATE INDEX JN_IND ON LLPSY_PK1_BPS_INDEX  (JN)  CREATE INDEX TN_IND ON LLPSY_PK1_BPS_INDEX  (TN)  CREATE NONCLUSTERED INDEX  REC_KEY_IND ON LLPSY_PK1_BPS_INDEX  ([REC_KEY]) 
DROP TABLE LLPSY_PK1_BPS_INDEX_1    
DROP TABLE LLPSY_PK1_BPS_INDEX_2     END

Он заканчивается этой ошибкой:

  1. SQLCODE -156
  2. SQLSTATE 37000
  3. Неверный синтаксис рядом сключевое слово PROCEDURE

Когда я запускаю этот SQL в SQL Manager, он работает без проблем.Когда я отслеживаю его в SQL Profiler, я получаю следующее:

declare @p1 int
set @p1=NULL
exec sp_prepare @p1 output,N'@P1 nvarchar(1000),@P2 nvarchar(1000),@P3 nvarchar(1000),@P4 nvarchar(1000)',N'CREATE PROCEDURE dbo.LLPSY_PK1_BPS_PROC_INDEX  AS BEGIN 
 IF EXISTS (select * from sysobjects where id = object_id(N''LLPSY_PK1_BPS_INDEX '') and OBJECTPROPERTY(id, N''IsTable'') = 1) DROP TABLE LLPSY_PK1_BPS_INDEX 
 IF EXISTS (select * from sysobjects where id = object_id(N''LLPSY_PK1_BPS_INDEX_1    '') and OBJECTPROPERTY(id, N''IsTable'') = 1) DROP TABLE LLPSY_PK1_BPS_INDEX_1    
 IF EXISTS (select * from sysobjects where id = object_id(N''LLPSY_PK1_BPS_INDEX_2    '') and OBJECTPROPERTY(id, N''IsTable'') = 1) DROP TABLE LLPSY_PK1_BPS_INDEX_2    
SELECT PAYMENT_REF=CASE C.ACNT_TYPE WHEN 1 THEN  CAST(SUBSTRING(A.TREFERENCE,CAST(01 AS int),CAST(30 AS int)) AS NCHAR(30))WHEN 0 THEN  CAST(SUBSTRING(A.TREFERENCE,CAST(01 AS int),CAST(30 AS int)) AS NCHAR(30))WHEN 2 THEN  CAST(SUBSTRING(A.TREFERENCE,CAST(01 AS int),CAST(30 AS int)) AS NCHAR(30))WHEN 4 THEN  CAST(SUBSTRING(A.TREFERENCE,CAST(01 AS int),CAST(30 AS int)) AS NCHAR(30))END ,A.ACCNT_CODE AS ACCOUNT,BANKNO=CASE WHEN E.BANK_ACNT_NUM IS NULL THEN''''ELSE E.BANK_ACNT_NUM END,AMOUNT=CASE WHEN A.AMOUNT>0 THEN A.AMOUNT ELSE A.AMOUNT*-1 END,A.D_C AS AMOUNT_DC,OTHER_AMOUNT=CASE WHEN A.OTHER_AMT>0 THEN A.OTHER_AMT ELSE A.OTHER_AMT*-1 END,A.D_C AS OTHER_AMOUNT_DC,CAST(A.ACCNT_CODE AS NCHAR(15))+CAST(A.PERIOD AS NCHAR(07))+CONVERT(CHAR(16),A.TRANS_DATETIME,112)AS LEDGER_KEY,CAST(A.JRNAL_NO AS NUMERIC(09))AS JN,CAST(A.JRNAL_LINE AS NUMERIC(09))AS TN,''A''AS BUDGET,'' ''AS LOCAL_CURR,'' ''AS COUNT,0 AS COUNTS,CAST('' ''AS NCHAR(80))AS TNS,C.DESCR AS ACCOUNT_NAME,A.DESCRIPTN AS DESCRIPTION,A.CONV_CODE,A.TREFERENCE AS TRANS_REF,'' ''AS MATCHED,C.ACNT_TYPE AS AT,'' ''AS DOUBLES,'' ''AS SPLIT,ADD_1=E.A,'' ''AS ADD_2,'' ''AS ADD_3,PAYMENT_ADD='' '' INTO LLPSY_PK1_BPS_INDEX_1    FROM PK1_A_SALFLDG AS A INNER JOIN PK1_ACNT AS C ON A.ACCNT_CODE=C.ACNT_CODE LEFT JOIN LLPSY_PK1_BNK_BKA_VIEW   AS E ON A.ACCNT_CODE=E.ACCOUNT AND E.A<>''M''  OR  A.ACCNT_CODE=E.ACCOUNT AND E.A= ''M''  AND A.ANAL_T9   =E.BDS       LEFT JOIN PK1_A_SALFLDG_LAD  AS M ON A.ACCNT_CODE=M.ACCNT_CODE AND A.JRNAL_NO=M.JRNAL_NO AND A.JRNAL_LINE=M.JRNAL_LINE WHERE(( A.ACCNT_CODE BETWEEN @P1 and @P2 AND C.ACNT_TYPE IN(1)))AND ALLOCATION NOT IN (''A'',''P'',''Y'',''C'',''R'',''2'',''W'') UNION SELECT PAYMENT_REF=CASE C.ACNT_TYPE WHEN 1 THEN  CAST(SUBSTRING(A.TREFERENCE,CAST(01 AS int),CAST(30 AS int)) AS NCHAR(30))WHEN 0 THEN  CAST(SUBSTRING(A.TREFERENCE,CAST(01 AS int),CAST(30 AS int)) AS NCHAR(30))WHEN 2 THEN  CAST(SUBSTRING(A.TREFERENCE,CAST(01 AS int),CAST(30 AS int)) AS NCHAR(30))WHEN 4 THEN  CAST(SUBSTRING(A.TREFERENCE,CAST(01 AS int),CAST(30 AS int)) AS NCHAR(30))END ,A.ACCNT_CODE AS ACCOUNT,BANKNO=CASE WHEN E.BANK_ACNT_NUM IS NULL THEN''''ELSE E.BANK_ACNT_NUM END,AMOUNT=CASE WHEN A.AMOUNT>0 THEN A.AMOUNT ELSE A.AMOUNT*-1 END,A.D_C AS AMOUNT_DC,OTHER_AMOUNT=CASE WHEN A.OTHER_AMT>0 THEN A.OTHER_AMT ELSE A.OTHER_AMT*-1 END,A.D_C AS OTHER_AMOUNT_DC,CAST(A.ACCNT_CODE AS NCHAR(15))+CAST(A.PERIOD AS NCHAR(07))+CONVERT(CHAR(16),A.TRANS_DATETIME,112)AS LEDGER_KEY,CAST(A.JRNAL_NO AS NUMERIC(09))AS JN,CAST(A.JRNAL_LINE AS NUMERIC(09))AS TN,''B''AS BUDGET,'' ''AS LOCAL_CURR,'' ''AS COUNT,0 AS COUNTS,CAST('' ''AS NCHAR(80))AS TNS,C.DESCR AS ACCOUNT_NAME,A.DESCRIPTN AS DESCRIPTION,A.CONV_CODE,A.TREFERENCE AS TRANS_REF,'' ''AS MATCHED,C.ACNT_TYPE AS AT,'' ''AS DOUBLES,'' ''AS SPLIT,ADD_1=E.A,'' ''AS ADD_2,'' ''AS ADD_3,PAYMENT_ADD='' ''                               FROM PK1_B_SALFLDG AS A INNER JOIN PK1_ACNT AS C ON A.ACCNT_CODE=C.ACNT_CODE LEFT JOIN LLPSY_PK1_BNK_BKA_VIEW   AS E ON A.ACCNT_CODE=E.ACCOUNT AND E.A<>''M''  OR  A.ACCNT_CODE=E.ACCOUNT AND E.A= ''M''  AND A.ANAL_T9   =E.BDS       LEFT JOIN PK1_A_SALFLDG_LAD  AS M ON A.ACCNT_CODE=M.ACCNT_CODE AND A.JRNAL_NO=M.JRNAL_NO AND A.JRNAL_LINE=M.JRNAL_LINE WHERE(( A.ACCNT_CODE BETWEEN @P3 and @P4 AND C.ACNT_TYPE IN(1)))AND ALLOCATION NOT IN (''A'',''P'',''Y'',''C'',''R'',''2'',''W'')SELECT PAYMENT_REF,ACCOUNT,BANKNO,AMOUNT,AMOUNT_DC,OTHER_AMOUNT,OTHER_AMOUNT_DC,LEDGER_KEY,JN,TN,BUDGET,LOCAL_CURR,COUNT,COUNTS,TNS,ACCOUNT_NAME,DESCRIPTION,CONV_CODE,TRANS_REF,MATCHED,AT,REC_KEY=IDENTITY(int,1,1),DOUBLES,SPLIT,ADD_1,ADD_2,ADD_3,PAYMENT_ADD INTO LLPSY_PK1_BPS_INDEX_2     FROM LLPSY_PK1_BPS_INDEX_1   SELECT PAYMENT_REF,ACCOUNT,BANKNO,AMOUNT,AMOUNT_DC,OTHER_AMOUNT,OTHER_AMOUNT_DC,LEDGER_KEY,JN,TN,BUDGET,LOCAL_CURR,COUNT,COUNTS,TNS,ACCOUNT_NAME,DESCRIPTION,CONV_CODE,TRANS_REF,MATCHED,AT,REC_KEY,DOUBLES,SPLIT,ADD_1,ADD_2,ADD_3 INTO dbo.LLPSY_PK1_BPS_INDEX  FROM LLPSY_PK1_BPS_INDEX_2    WHERE ISNUMERIC(LTRIM(PAYMENT_REF))=1   SET IDENTITY_INSERT LLPSY_PK1_BPS_INDEX  ON  INSERT INTO LLPSY_PK1_BPS_INDEX  (PAYMENT_REF,ACCOUNT,BANKNO,AMOUNT,AMOUNT_DC,OTHER_AMOUNT,OTHER_AMOUNT_DC,LEDGER_KEY,JN,TN,BUDGET,LOCAL_CURR,COUNT,COUNTS,TNS,ACCOUNT_NAME,DESCRIPTION,CONV_CODE,TRANS_REF,MATCHED,AT,REC_KEY,DOUBLES,SPLIT,ADD_1,ADD_2,ADD_3) SELECT dbo.LLPSY_Remove_AB_String(PAYMENT_REF), ACCOUNT,BANKNO,AMOUNT,AMOUNT_DC,OTHER_AMOUNT,OTHER_AMOUNT_DC,LEDGER_KEY,JN,TN,BUDGET,LOCAL_CURR,COUNT,COUNTS,TNS,ACCOUNT_NAME,DESCRIPTION,CONV_CODE,TRANS_REF,MATCHED,AT,REC_KEY,DOUBLES,SPLIT,ADD_1,ADD_2,ADD_3 FROM LLPSY_PK1_BPS_INDEX_2    WHERE dbo.LLPSY_Remove_AB_String(PAYMENT_REF)<>'''' AND  dbo.LLPSY_Remove_AB_String(PAYMENT_REF)<>PAYMENT_REF
  SET IDENTITY_INSERT LLPSY_PK1_BPS_INDEX  ON  INSERT INTO LLPSY_PK1_BPS_INDEX  (PAYMENT_REF,ACCOUNT,BANKNO,AMOUNT,AMOUNT_DC,OTHER_AMOUNT,OTHER_AMOUNT_DC,LEDGER_KEY,JN,TN,BUDGET,LOCAL_CURR,COUNT,COUNTS,TNS,ACCOUNT_NAME,DESCRIPTION,CONV_CODE,TRANS_REF,MATCHED,AT,REC_KEY,DOUBLES,SPLIT,ADD_1,ADD_2,ADD_3) SELECT dbo.LLPSY_Remove_AB_String(PAYMENT_ADD)AS PAYMENT_REF, ACCOUNT,BANKNO,AMOUNT,AMOUNT_DC,OTHER_AMOUNT,OTHER_AMOUNT_DC,LEDGER_KEY,JN,TN,BUDGET,LOCAL_CURR,COUNT,COUNTS,TNS,ACCOUNT_NAME,DESCRIPTION,CONV_CODE,TRANS_REF,MATCHED,AT,REC_KEY,DOUBLES,SPLIT,ADD_1,ADD_2,ADD_3 FROM LLPSY_PK1_BPS_INDEX_2    WHERE PAYMENT_ADD IS NOT NULL AND PAYMENT_ADD<>'''' AND dbo.LLPSY_Remove_AB_String(PAYMENT_ADD)<>'''' CREATE INDEX PAYMENT_REF_IND ON LLPSY_PK1_BPS_INDEX  (PAYMENT_REF)  CREATE INDEX BANKNO_IND ON LLPSY_PK1_BPS_INDEX  (BANKNO)  CREATE INDEX LEDGER_KEY_IND ON LLPSY_PK1_BPS_INDEX  (LEDGER_KEY)  CREATE INDEX JN_IND ON LLPSY_PK1_BPS_INDEX  (JN)  CREATE INDEX TN_IND ON LLPSY_PK1_BPS_INDEX  (TN)  CREATE NONCLUSTERED INDEX  REC_KEY_IND ON LLPSY_PK1_BPS_INDEX  ([REC_KEY]) 
DROP TABLE LLPSY_PK1_BPS_INDEX_1    
DROP TABLE LLPSY_PK1_BPS_INDEX_2     END',1
select @p1

И запуск этого кода из SQL Profiler вызывает ту же ошибку, что и во встроенном SQL.Пожалуйста, что здесь не так?

1 Ответ

0 голосов
/ 19 октября 2018

Не ответ, но слишком долго, как комментарий.У вас много чрезмерно сложного кода, который очень выиграл бы от относительно простых изменений.У вас есть:

SELECT PAYMENT_REF=CASE C.ACNT_TYPE 
WHEN 1 THEN  CAST(SUBSTRING(A.TREFERENCE,CAST(01 AS int), CAST(30 AS int)) AS NCHAR(30))
WHEN 0 THEN  CAST(SUBSTRING(A.TREFERENCE,CAST(01 AS int),CAST(30 AS int)) AS NCHAR(30))
WHEN 2 THEN  CAST(SUBSTRING(A.TREFERENCE,CAST(01 AS int),CAST(30 AS int)) AS NCHAR(30))
WHEN 4 THEN  CAST(SUBSTRING(A.TREFERENCE,CAST(01 AS int),CAST(30 AS int)) AS NCHAR(30)) END ,
  • Вы можете просто привести выражение case к желаемому типу.Вам не нужно разыгрывать каждое условие.
  • Для всех, кто придет после вас, введите свои логические выражения IN ORDER .
  • числовые литералы будут неявно приводиться к соответствующему типу данных.Значения, такие как 1 и 30, будут интерпретироваться как целые числа.Нет необходимости разыгрывать их.
  • Вы используете одну и ту же формулу в каждом случае.Так почему же вы слишком усложняете, когда пишете одно и то же 4 раза.
  • подстрока (1, 30) совпадает с левой (30).Опять же, почему осложнение?

Таким образом, эту единую формулу можно сжать и упростить до:

select PAYMENT_REF = cast(case when C.ACNT_TYPE in (0, 1, 2, 4) 
    then left(A.TREFERENCE, 30) else NULL end as NCHAR(30)),

При желании вы можете опустить часть ELSE.Я предпочитаю включать его, поскольку он указывает любому читающему код, что автор действительно задумывался о том, что происходит, когда нет совпадения во время оценки.А простое форматирование делает код значительно проще для чтения и, следовательно, для понимания.

Наконец, уничтожение и создание постоянных таблиц в базе данных - это проблема безопасности и проблема эффективности.Гораздо лучше разрешить квалифицированному dba определять размещение, организацию и индексирование этой таблицы, а затем встраивать ее в логику приложения.Вы не рассматривали разрешения для этих таблиц, что также имеет значительные последствия.Там нет кластерного индекса AFAIK - это часто проблема.

Похоже, что лучший подход к вашей цели - просто создать хранимую процедуру один раз.Вы создаете с ДВА (не запутанные четыре у вас сейчас) параметры.Ваш dba создаст единственную таблицу, которая является целью вашей логики - остальные 2 - просто временное хранилище.В грубом, сокращенном и неполном псевдокоде:

create procedure dbo.LLPSY_PK1_BPS_PROC_INDEX (@ACCT_START int, @ACCT_END int) as 
begin 
    insert ... 
    select ... 
    where ( A.ACCNT_CODE BETWEEN @ACCT_START and @ACCT_END) ... 
    ...
end;

Есть и другие проблемы, которые необходимо решить, но вам нужно с чего-то начать.Использование UNION (не UNION ALL), многократное использование [select ... into ...], построение процедуры, которая зависит от логики приложения в конкретный момент времени и зависит от нее - все эти вещисоздают будущую проблему отладки и обслуживания.И еще один последний комментарий - ваш код предполагает конкретную схему для большинства операторов, но одну очень важную (оператор процедуры создания).Либо предполагайте везде, либо предполагайте, что нет.Лучше вообще не предполагать без уважительной причины.

...