SQL - отладка динамического кода PIVOT с помощью UNION ALL

Мне нужна помощь! Первая часть моего кода выглядит следующим образом:

DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX);

SET @cols= STUFF((SELECT ','+QUOTENAME(c.CURCODE) FROM (

(

SELECT DISTINCT b.CURCODE,a.TRCURR FROM LG_011_BNCREDITCARD a INNER JOIN L_CURRENCYLIST b 
ON a.TRCURR=b.CURTYPE OR (a.TRCURR=0 AND b.CURTYPE=160)

)

UNION

(

SELECT DISTINCT b.CURCODE,a.TRCURR

FROM LG_011_LEASINGPAYMENTSLNS a

INNER JOIN LG_011_PURCHOFFER z
ON a.LEASINGREF=z.LEASINGREF

INNER JOIN
(SELECT 
MAX(LOGICALREF) LOGICALREF,
LEASINGREF
FROM LG_011_PURCHOFFER
GROUP BY LEASINGREF) y
ON z.LOGICALREF=y.LOGICALREF

INNER JOIN L_CURRENCYLIST b
ON a.TRCURR=b.CURTYPE OR (a.TRCURR=0 AND b.CURTYPE=160)

WHERE z.STATUS=4

)

UNION

(

SELECT DISTINCT cur.CURCODE,cs.TRCURR FROM 

LG_011_01_CSTRANS a

INNER JOIN

(
SELECT 
CSREF,
MAX(STATNO) [STATNO]

FROM LG_011_01_CSTRANS
GROUP BY CSREF) b
ON a.CSREF=b.CSREF AND a.STATNO=b.STATNO

INNER JOIN LG_011_01_CSCARD cs ON a.CSREF=cs.LOGICALREF
INNER JOIN L_CURRENCYLIST cur ON cs.TRCURR=cur.CURTYPE OR (cs.TRCURR=0 AND cur.CURTYPE=160)

WHERE cs.DOC=3 AND cs.CURRSTAT=9 AND cur.FIRMNR=11

)

UNION

(

SELECT DISTINCT cur.CURCODE, pt.TRCURR

FROM LG_011_01_PAYTRANS pt
INNER JOIN LG_011_CLCARD cl ON pt.CARDREF=cl.LOGICALREF
INNER JOIN L_CURRENCYLIST cur ON pt.TRCURR=cur.CURTYPE OR (pt.TRCURR=0 AND cur.CURTYPE=160)

WHERE pt.MODULENR IN (4,5) AND pt.PAID=0 AND pt.SIGN=1 AND cl.CODE LIKE '320%' AND cl.SPECODE IN ('OTOMATİK','ZORUNLU')

)

) c ORDER BY c.TRCURR FOR XML PATH(''), TYPE 
).value('.','NVARCHAR(MAX)'),1,1,'')

До сих пор проблем не было. Используя код выше,

SELECT @cols  

дает вывод:

[TL],[USD],[EUR]

Вторая часть запроса, где проблема возникает. Код структурирован следующим образом:

SET @query ='

SELECT

col1 [TÜR],
col2 [KOD],
col3 [BANKA/CARİ],
col4 [BANKA HESABI],
col5 [AÇIKLAMA],
col6 [VADE],
' + @cols + '

FROM

(
Table 1

UNION ALL

Table 2

UNION ALL

Table 3

UNION ALL

Table 4

) x

PIVOT
(
SUM(AMOUNT)
FOR CURCODE IN ('+ @cols+ ')

) xx

ORDER BY xx.col6,xx.TRCURR, xx.col1, xx.col3, xx.col4, xx.col2
'

execute(@query)

Вторая часть не работает. Я могу заставить его работать, делая три вещи:

1- Создание неподвижного стержня (т.е. замена '+ @cols +' с [TL],[USD],[EUR]

2- Извлечение Таблицы 2, Таблицы 3 или Таблицы 4 из комбинаций UNION ALL. Каким-то образом удаление только одной таблицы делает работу динамического центра.

3. Я могу удалить одну из Таблицы 2, Таблицы 3 или Таблицы 4 и снова добавить одну из оставшихся таблиц в качестве еще одного дополнения UNION ALL. Странно, это работает также. Таким образом, проблема может заключаться в том, что может быть один аспект четырех таблиц вместе, который мешает выражению PIVOT.

Но я хотел бы включить все таблицы с 1 по 4, и я хотел бы иметь динамический стержень, который настраивает себя на изменения!

Обратите внимание, что если я запускаю инструкцию SELECT без конструкции PIVOT со всеми UNION ALLs, код также прекрасно работает (как я указал ниже)

Мой оригинальный код:

DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX);

SET @cols= STUFF((SELECT ','+QUOTENAME(c.CURCODE) FROM (

(

SELECT DISTINCT b.CURCODE,a.TRCURR FROM LG_011_BNCREDITCARD a INNER JOIN L_CURRENCYLIST b 
ON a.TRCURR=b.CURTYPE OR (a.TRCURR=0 AND b.CURTYPE=160)

)

UNION

(

SELECT DISTINCT b.CURCODE,a.TRCURR

FROM LG_011_LEASINGPAYMENTSLNS a

INNER JOIN LG_011_PURCHOFFER z
ON a.LEASINGREF=z.LEASINGREF

INNER JOIN
(SELECT 
MAX(LOGICALREF) LOGICALREF,
LEASINGREF
FROM LG_011_PURCHOFFER
GROUP BY LEASINGREF) y
ON z.LOGICALREF=y.LOGICALREF

INNER JOIN L_CURRENCYLIST b
ON a.TRCURR=b.CURTYPE OR (a.TRCURR=0 AND b.CURTYPE=160)

WHERE z.STATUS=4

)

UNION

(

SELECT DISTINCT cur.CURCODE,cs.TRCURR FROM 

LG_011_01_CSTRANS a

INNER JOIN

(
SELECT 
CSREF,
MAX(STATNO) [STATNO]

FROM LG_011_01_CSTRANS
GROUP BY CSREF) b
ON a.CSREF=b.CSREF AND a.STATNO=b.STATNO

INNER JOIN LG_011_01_CSCARD cs ON a.CSREF=cs.LOGICALREF
INNER JOIN L_CURRENCYLIST cur ON cs.TRCURR=cur.CURTYPE OR (cs.TRCURR=0 AND cur.CURTYPE=160)

WHERE cs.DOC=3 AND cs.CURRSTAT=9 AND cur.FIRMNR=11

)

UNION

(

SELECT DISTINCT cur.CURCODE, pt.TRCURR

FROM LG_011_01_PAYTRANS pt
INNER JOIN LG_011_CLCARD cl ON pt.CARDREF=cl.LOGICALREF
INNER JOIN L_CURRENCYLIST cur ON pt.TRCURR=cur.CURTYPE OR (pt.TRCURR=0 AND cur.CURTYPE=160)

WHERE pt.MODULENR IN (4,5) AND pt.PAID=0 AND pt.SIGN=1 AND cl.CODE LIKE '320%' AND cl.SPECODE IN ('OTOMATİK','ZORUNLU')

)

) c ORDER BY c.TRCURR FOR XML PATH(''), TYPE 
).value('.','NVARCHAR(MAX)'),1,1,'')


SET @query ='

SELECT

col1 [TÜR],
col2 [KOD],
col3 [BANKA/CARİ],
col4 [BANKA HESABI],
col5 [AÇIKLAMA],
col6 [VADE],
'+ @cols +'

FROM

(

(

SELECT
''LEASİNG'' [col1],
 d.REGNR [col2],
 cl.DEFINITION_ [col3],
 '''' [col4],
 d.DESCRIPTION [col5],
 c.PAYMENTDATE [col6],
 a.KDVLI- Isnull(b.KDVLI,0) [AMOUNT],
 c.TRCURR [TRCURR],
 e.CURCODE [CURCODE]


FROM
(SELECT
LOGICALREF,
SUM(PAYMENTTOTAL) AS KDVSIZ,
SUM(INTTOTAL) AS FAIZ,
SUM(MAINTOTAL) AS ANAPARA,
SUM(VATINPAYMENTTOTAL-PAYMENTTOTAL) AS KDV,
SUM(VATINPAYMENTTOTAL) AS KDVLI

FROM LG_011_LEASINGPAYMENTSLNS
WHERE TRANSTYPE=0
GROUP BY LOGICALREF) a

LEFT OUTER JOIN

(SELECT
PARENTREF,
SUM(PAYMENTTOTAL) AS KDVSIZ,
SUM(INTTOTAL) AS FAIZ,
SUM(MAINTOTAL) AS ANAPARA,
SUM(VATINPAYMENTTOTAL-PAYMENTTOTAL) AS KDV,
SUM(VATINPAYMENTTOTAL) AS KDVLI
FROM LG_011_LEASINGPAYMENTSLNS
WHERE TRANSTYPE=1
GROUP BY PARENTREF
) b 
ON a.LOGICALREF= b.PARENTREF

INNER JOIN
LG_011_LEASINGPAYMENTSLNS c
ON a.LOGICALREF=c.LOGICALREF


INNER JOIN

LG_011_LEASINGREG d
ON c.LEASINGREF=d.LOGICALREF

INNER JOIN
LG_011_PURCHOFFER z
ON c.LEASINGREF=z.LEASINGREF

INNER JOIN
(SELECT 
MAX(LOGICALREF) LOGICALREF,
LEASINGREF,
CLIENTREF
FROM LG_011_PURCHOFFER
GROUP BY CLIENTREF,LEASINGREF) y
ON z.LOGICALREF=y.LOGICALREF

INNER JOIN LG_011_CLCARD cl
ON z.CLIENTREF=cl.LOGICALREF

INNER JOIN L_CURRENCYLIST e
ON c.TRCURR=e.CURTYPE OR (c.TRCURR=0 AND e.CURTYPE=160)


WHERE e.FIRMNR=11 AND z.STATUS=4 AND a.KDVLI - Isnull(b.KDVLI,0)<>0

)

UNION ALL

(

SELECT
''ÇEK'',
cs.NEWSERINO,
bn.DEFINITION_,
ban.DEFINITION_,
cl.DEFINITION_,
cs.DUEDATE,
cs.AMOUNT,
cs.TRCURR,
cur.CURCODE

FROM

LG_011_01_CSTRANS a

INNER JOIN

(
SELECT 
CSREF,
MAX(STATNO) [STATNO]

FROM LG_011_01_CSTRANS
GROUP BY CSREF) b
ON a.CSREF=b.CSREF AND a.STATNO=b.STATNO

INNER JOIN LG_011_01_CSCARD cs ON a.CSREF=cs.LOGICALREF
INNER JOIN LG_011_BANKACC ban ON cs.OURBANKREF=ban.LOGICALREF
INNER JOIN LG_011_BNCARD bn ON ban.BANKREF=bn.LOGICALREF
INNER JOIN L_CURRENCYLIST cur ON cs.TRCURR=cur.CURTYPE OR (cs.TRCURR=0 AND cur.CURTYPE=160)
INNER JOIN LG_011_CLCARD cl ON a.CARDREF=cl.LOGICALREF

WHERE cs.DOC=3 AND cs.CURRSTAT=9 AND cur.FIRMNR=11

)

UNION ALL

(

SELECT
CASE WHEN cl.SPECODE=''OTOMATİK'' THEN ''OTOMATİK ÖDEME'' WHEN cl.SPECODE=''ZORUNLU'' THEN ''ZORUNLU CARİ'' END,
CASE WHEN pt.MODULENR=5 AND pt.TRCODE=14 THEN clf.DOCODE WHEN pt.MODULENR=5 AND pt.TRCODE<>14 THEN clf.TRANNO ELSE inv.FICHENO END,
cl.DEFINITION_,
'''',
'''',
pt.DATE_,
pt.TOTAL,
pt.TRCURR,
cur.CURCODE

FROM LG_011_01_PAYTRANS pt
INNER JOIN LG_011_CLCARD cl ON pt.CARDREF=cl.LOGICALREF
LEFT OUTER JOIN LG_011_01_INVOICE inv ON pt.FICHEREF=inv.LOGICALREF
LEFT OUTER JOIN LG_011_01_CLFLINE clf ON pt.FICHEREF=clf.LOGICALREF
INNER JOIN L_CURRENCYLIST cur ON pt.TRCURR=cur.CURTYPE OR (pt.TRCURR=0 AND cur.CURTYPE=160)

WHERE pt.MODULENR IN (4,5) AND pt.PAID=0 AND pt.SIGN=1 AND cl.CODE LIKE ''320%'' AND cl.SPECODE IN (''OTOMATİK'',''ZORUNLU'') AND cur.FIRMNR=11

)

UNION ALL

(
SELECT
 CASE d.SPECODE WHEN '''' THEN ''KREDİ'' WHEN ''FORWARD'' THEN ''FORWARD'' END [TÜR],
 d.CODE,
 f.DEFINITION_,
 g.DEFINITION_,
 d.NAME_,
 b.DUEDATE,
 a.TAKSIT - Isnull(c.TAKSIT,0) AS TAKSIT,
 d.TRCURR,
 e.CURCODE

 FROM
    (SELECT 
 PARENTREF,
 SUM(TOTAL) AS ANAPARA,
 SUM(INTTOTAL) AS FAIZ,
 SUM(BSMVTOTAL) AS BSMV,
 SUM(KKDFTOTAL) AS KKDF,
 SUM(TOTAL+INTTOTAL+BSMVTOTAL+KKDFTOTAL) AS TAKSIT

        FROM LG_011_BNCREPAYTR 
        WHERE TRANSTYPE = 0 
        GROUP BY PARENTREF) a 
INNER JOIN (SELECT
 LOGICALREF,
 PARENTREF,
 CREDITREF,
 DUEDATE,
 OPRDATE
 FROM LG_011_BNCREPAYTR
                WHERE TRANSTYPE = 0) b
ON a.PARENTREF=b.PARENTREF

LEFT OUTER JOIN (SELECT
 PARENTREF,
 SUM(TOTAL) AS ANAPARA,
 SUM(INTTOTAL) AS FAIZ,
 SUM(BSMVTOTAL) AS BSMV,
 SUM(KKDFTOTAL) AS KKDF,
 SUM(TOTAL+INTTOTAL+BSMVTOTAL+KKDFTOTAL) AS TAKSIT
        FROM LG_011_BNCREPAYTR 
        WHERE TRANSTYPE = 1 
        GROUP BY PARENTREF) c 
ON b.LOGICALREF = c.PARENTREF

INNER JOIN LG_011_BNCREDITCARD d
ON b.CREDITREF=d.LOGICALREF

INNER JOIN L_CURRENCYLIST e
ON d.TRCURR=e.CURTYPE OR (d.TRCURR=0 AND e.CURTYPE=160)

INNER JOIN LG_011_BNCARD f
ON d.BNCRREF=f.LOGICALREF

INNER JOIN LG_011_BANKACC g
ON d.BNACCREF=g.LOGICALREF

WHERE e.FIRMNR=11 AND a.TAKSIT - Isnull(c.TAKSIT,0)<>0
)

) x

PIVOT

(

SUM(AMOUNT)
FOR CURCODE IN ('+ @cols +')

) xx

ORDER BY xx.col6,xx.TRCURR, xx.col1, xx.col3, xx.col4, xx.col2
'

execute(@query)

и я получаю следующую ошибку при выполнении запроса:

Msg 102, Level 15, State 1, Line 205
Incorrect syntax near ','.

Я до сих пор не смог определить проблему. Я не думаю, что с моим кодом есть логическая проблема, так как обе части моего кода могут работать независимо, но когда я присоединяюсь к ним с помощью оператора PIVOT, это дает сбой. Не могли бы вы просмотреть мой код, чтобы убедиться, что я делаю какие-либо ошибки в своих рассуждениях или синтаксисе?

Спасибо!


ОБНОВИТЬ

Я точно знаю, что мой UNION ALLS работает. Ниже приведен код, который идет под конструкцией PIVOT в моем исходном коде:

(

SELECT
'ÇEK' [col1],
cs.NEWSERINO [col2],
bn.DEFINITION_ [col3],
ban.DEFINITION_ [col4],
cl.DEFINITION_ [col5],
cs.DUEDATE [col6],
cs.AMOUNT [AMOUNT],
cs.TRCURR [TRCURR],
cur.CURCODE [CURCODE]

FROM

LG_011_01_CSTRANS a

INNER JOIN

(
SELECT 
CSREF,
MAX(STATNO) [STATNO]

FROM LG_011_01_CSTRANS
GROUP BY CSREF) b
ON a.CSREF=b.CSREF AND a.STATNO=b.STATNO

INNER JOIN LG_011_01_CSCARD cs ON a.CSREF=cs.LOGICALREF
INNER JOIN LG_011_BANKACC ban ON cs.OURBANKREF=ban.LOGICALREF
INNER JOIN LG_011_BNCARD bn ON ban.BANKREF=bn.LOGICALREF
INNER JOIN L_CURRENCYLIST cur ON cs.TRCURR=cur.CURTYPE OR (cs.TRCURR=0 AND cur.CURTYPE=160)
INNER JOIN LG_011_CLCARD cl ON a.CARDREF=cl.LOGICALREF

WHERE cs.DOC=3 AND cs.CURRSTAT=9 AND cur.FIRMNR=11

)

UNION ALL

(
SELECT
'LEASİNG',
 d.REGNR,
 cl.DEFINITION_,
 '',
 d.DESCRIPTION,
 c.PAYMENTDATE,
 a.KDVLI- Isnull(b.KDVLI,0),
 c.TRCURR,
 e.CURCODE


FROM
(SELECT
LOGICALREF,
SUM(PAYMENTTOTAL) AS KDVSIZ,
SUM(INTTOTAL) AS FAIZ,
SUM(MAINTOTAL) AS ANAPARA,
SUM(VATINPAYMENTTOTAL-PAYMENTTOTAL) AS KDV,
SUM(VATINPAYMENTTOTAL) AS KDVLI

FROM LG_011_LEASINGPAYMENTSLNS
WHERE TRANSTYPE=0
GROUP BY LOGICALREF) a

LEFT OUTER JOIN

(SELECT
PARENTREF,
SUM(PAYMENTTOTAL) AS KDVSIZ,
SUM(INTTOTAL) AS FAIZ,
SUM(MAINTOTAL) AS ANAPARA,
SUM(VATINPAYMENTTOTAL-PAYMENTTOTAL) AS KDV,
SUM(VATINPAYMENTTOTAL) AS KDVLI
FROM LG_011_LEASINGPAYMENTSLNS
WHERE TRANSTYPE=1
GROUP BY PARENTREF
) b 
ON a.LOGICALREF= b.PARENTREF

INNER JOIN
LG_011_LEASINGPAYMENTSLNS c
ON a.LOGICALREF=c.LOGICALREF


INNER JOIN

LG_011_LEASINGREG d
ON c.LEASINGREF=d.LOGICALREF

INNER JOIN
LG_011_PURCHOFFER z
ON c.LEASINGREF=z.LEASINGREF

INNER JOIN
(SELECT 
MAX(LOGICALREF) LOGICALREF,
LEASINGREF,
CLIENTREF
FROM LG_011_PURCHOFFER
GROUP BY CLIENTREF,LEASINGREF) y
ON z.LOGICALREF=y.LOGICALREF

INNER JOIN LG_011_CLCARD cl
ON z.CLIENTREF=cl.LOGICALREF

INNER JOIN L_CURRENCYLIST e
ON c.TRCURR=e.CURTYPE OR (c.TRCURR=0 AND e.CURTYPE=160)


WHERE e.FIRMNR=11 AND z.STATUS=4 AND a.KDVLI - Isnull(b.KDVLI,0)<>0

)

UNION ALL

(

SELECT
CASE WHEN cl.SPECODE='OTOMATİK' THEN 'OTOMATİK ÖDEME' WHEN cl.SPECODE='ZORUNLU' THEN 'ZORUNLU CARİ' END,
CASE WHEN pt.MODULENR=5 AND pt.TRCODE=14 THEN clf.DOCODE WHEN pt.MODULENR=5 AND pt.TRCODE<>14 THEN clf.TRANNO ELSE inv.FICHENO END,
cl.DEFINITION_,
'',
'',
pt.DATE_,
pt.TOTAL,
pt.TRCURR,
cur.CURCODE

FROM LG_011_01_PAYTRANS pt
INNER JOIN LG_011_CLCARD cl ON pt.CARDREF=cl.LOGICALREF
LEFT OUTER JOIN LG_011_01_INVOICE inv ON pt.FICHEREF=inv.LOGICALREF
LEFT OUTER JOIN LG_011_01_CLFLINE clf ON pt.FICHEREF=clf.LOGICALREF
INNER JOIN L_CURRENCYLIST cur ON pt.TRCURR=cur.CURTYPE OR (pt.TRCURR=0 AND cur.CURTYPE=160)

WHERE pt.MODULENR IN (4,5) AND pt.PAID=0 AND pt.SIGN=1 AND cl.CODE LIKE '320%' AND cl.SPECODE IN ('OTOMATİK','ZORUNLU') AND cur.FIRMNR=11

)

UNION ALL

(
SELECT
 CASE d.SPECODE WHEN '' THEN 'KREDİ' WHEN 'FORWARD' THEN 'FORWARD' END [TÜR],
 d.CODE,
 f.DEFINITION_,
 g.DEFINITION_,
 d.NAME_,
 b.DUEDATE,
 a.TAKSIT - Isnull(c.TAKSIT,0) AS TAKSIT,
 d.TRCURR,
 e.CURCODE

 FROM
    (SELECT 
 PARENTREF,
 SUM(TOTAL) AS ANAPARA,
 SUM(INTTOTAL) AS FAIZ,
 SUM(BSMVTOTAL) AS BSMV,
 SUM(KKDFTOTAL) AS KKDF,
 SUM(TOTAL+INTTOTAL+BSMVTOTAL+KKDFTOTAL) AS TAKSIT

        FROM LG_011_BNCREPAYTR 
        WHERE TRANSTYPE = 0 
        GROUP BY PARENTREF) a 
INNER JOIN (SELECT
 LOGICALREF,
 PARENTREF,
 CREDITREF,
 DUEDATE,
 OPRDATE
 FROM LG_011_BNCREPAYTR
                WHERE TRANSTYPE = 0) b
ON a.PARENTREF=b.PARENTREF

LEFT OUTER JOIN (SELECT
 PARENTREF,
 SUM(TOTAL) AS ANAPARA,
 SUM(INTTOTAL) AS FAIZ,
 SUM(BSMVTOTAL) AS BSMV,
 SUM(KKDFTOTAL) AS KKDF,
 SUM(TOTAL+INTTOTAL+BSMVTOTAL+KKDFTOTAL) AS TAKSIT
        FROM LG_011_BNCREPAYTR 
        WHERE TRANSTYPE = 1 
        GROUP BY PARENTREF) c 
ON b.LOGICALREF = c.PARENTREF

INNER JOIN LG_011_BNCREDITCARD d
ON b.CREDITREF=d.LOGICALREF

INNER JOIN L_CURRENCYLIST e
ON d.TRCURR=e.CURTYPE OR (d.TRCURR=0 AND e.CURTYPE=160)

INNER JOIN LG_011_BNCARD f
ON d.BNCRREF=f.LOGICALREF

INNER JOIN LG_011_BANKACC g
ON d.BNACCREF=g.LOGICALREF

WHERE e.FIRMNR=11 AND a.TAKSIT - Isnull(c.TAKSIT,0)<>0
)

Код работает сам по себе, но когда я помещаю его в структуру PIVOT, он не работает. Пожалуйста помоги! Или вы можете сказать мне метод, который я могу использовать вместо PIVOT, который даст мне тот же результат?


ОБНОВИТЬ

Я думаю, что что-то не так с длиной моего запроса, как при запуске print @queryЯ получаю следующее (Спасибо @KumarHarsh за то, что указали мне правильный путь!):

SELECT

col1 [TÜR],
col2 [KOD],
col3 [BANKA/CARİ],
col4 [BANKA HESABI],
col5 [AÇIKLAMA],
col6 [VADE],
[TL],[USD],[EUR]

FROM

(

(

SELECT
'LEASİNG' [col1],
 d.REGNR [col2],
 cl.DEFINITION_ [col3],
 '' [col4],
 d.DESCRIPTION [col5],
 c.PAYMENTDATE [col6],
 a.KDVLI- Isnull(b.KDVLI,0) [AMOUNT],
 c.TRCURR [TRCURR],
 e.CURCODE [CURCODE]


FROM
(SELECT
LOGICALREF,
SUM(PAYMENTTOTAL) AS KDVSIZ,
SUM(INTTOTAL) AS FAIZ,
SUM(MAINTOTAL) AS ANAPARA,
SUM(VATINPAYMENTTOTAL-PAYMENTTOTAL) AS KDV,
SUM(VATINPAYMENTTOTAL) AS KDVLI

FROM LG_011_LEASINGPAYMENTSLNS
WHERE TRANSTYPE=0
GROUP BY LOGICALREF) a

LEFT OUTER JOIN

(SELECT
PARENTREF,
SUM(PAYMENTTOTAL) AS KDVSIZ,
SUM(INTTOTAL) AS FAIZ,
SUM(MAINTOTAL) AS ANAPARA,
SUM(VATINPAYMENTTOTAL-PAYMENTTOTAL) AS KDV,
SUM(VATINPAYMENTTOTAL) AS KDVLI
FROM LG_011_LEASINGPAYMENTSLNS
WHERE TRANSTYPE=1
GROUP BY PARENTREF
) b 
ON a.LOGICALREF= b.PARENTREF

INNER JOIN
LG_011_LEASINGPAYMENTSLNS c
ON a.LOGICALREF=c.LOGICALREF


INNER JOIN

LG_011_LEASINGREG d
ON c.LEASINGREF=d.LOGICALREF

INNER JOIN
LG_011_PURCHOFFER z
ON c.LEASINGREF=z.LEASINGREF

INNER JOIN
(SELECT 
MAX(LOGICALREF) LOGICALREF,
LEASINGREF,
CLIENTREF
FROM LG_011_PURCHOFFER
GROUP BY CLIENTREF,LEASINGREF) y
ON z.LOGICALREF=y.LOGICALREF

INNER JOIN LG_011_CLCARD cl
ON z.CLIENTREF=cl.LOGICALREF

INNER JOIN L_CURRENCYLIST e
ON c.TRCURR=e.CURTYPE OR (c.TRCURR=0 AND e.CURTYPE=160)


WHERE e.FIRMNR=11 AND z.STATUS=4 AND a.KDVLI - Isnull(b.KDVLI,0)<>0

)

UNION ALL

(

SELECT
'ÇEK',
cs.NEWSERINO,
bn.DEFINITION_,
ban.DEFINITION_,
cl.DEFINITION_,
cs.DUEDATE,
cs.AMOUNT,
cs.TRCURR,
cur.CURCODE

FROM

LG_011_01_CSTRANS a

INNER JOIN

(
SELECT 
CSREF,
MAX(STATNO) [STATNO]

FROM LG_011_01_CSTRANS
GROUP BY CSREF) b
ON a.CSREF=b.CSREF AND a.STATNO=b.STATNO

INNER JOIN LG_011_01_CSCARD cs ON a.CSREF=cs.LOGICALREF
INNER JOIN LG_011_BANKACC ban ON cs.OURBANKREF=ban.LOGICALREF
INNER JOIN LG_011_BNCARD bn ON ban.BANKREF=bn.LOGICALREF
INNER JOIN L_CURRENCYLIST cur ON cs.TRCURR=cur.CURTYPE OR (cs.TRCURR=0 AND cur.CURTYPE=160)
INNER JOIN LG_011_CLCARD cl ON a.CARDREF=cl.LOGICALREF

WHERE cs.DOC=3 AND cs.CURRSTAT=9 AND cur.FIRMNR=11

)

UNION ALL

(

SELECT
CASE WHEN cl.SPECODE='OTOMATİK' THEN 'OTOMATİK ÖDEME' WHEN cl.SPECODE='ZORUNLU' THEN 'ZORUNLU CARİ' END,
CASE WHEN pt.MODULENR=5 AND pt.TRCODE=14 THEN clf.DOCODE WHEN pt.MODULENR=5 AND pt.TRCODE<>14 THEN clf.TRANNO ELSE inv.FICHENO END,
cl.DEFINITION_,
'',
'',
pt.DATE_,
pt.TOTAL,
pt.TRCURR,
cur.CURCODE

FROM LG_011_01_PAYTRANS pt
INNER JOIN LG_011_CLCARD cl ON pt.CARDREF=cl.LOGICALREF
LEFT OUTER JOIN LG_011_01_INVOICE inv ON pt.FICHEREF=inv.LOGICALREF
LEFT OUTER JOIN LG_011_01_CLFLINE clf ON pt.FICHEREF=clf.LOGICALREF
INNER JOIN L_CURRENCYLIST cur ON pt.TRCURR=cur.CURTYPE OR (pt.TRCURR=0 AND cur.CURTYPE=160)

WHERE pt.MODULENR IN (4,5) AND pt.PAID=0 AND pt.SIGN=1 AND cl.CODE LIKE '320%' AND cl.SPECODE IN ('OTOMATİK','ZORUNLU') AND cur.FIRMNR=11

)

UNION ALL

(
SELECT
 CASE d.SPECODE WHEN '' THEN 'KREDİ' WHEN 'FORWARD' THEN 'FORWARD' END [TÜR],
 d.CODE,
 f.DEFINITION_,
 g.DEFINITION_,
 d.NAME_,
 b.DUEDATE,
 a.TAKSIT - Isnull(c.TAKSIT,0) AS TAKSIT,
 d.TRCURR,
 e.CURCODE

 FROM
    (SELECT 
 PARENTREF,
 SUM(TOTAL) AS ANAPARA,
 SUM(INTTOTAL) AS FAIZ,
 SUM(BSMVTOTAL) AS BSMV,
 SUM(KKDFTOTAL) AS KKDF,
 SUM(TOTAL+INTTOTAL+BSMVTOTAL+KKDFTOTAL) AS TAKSIT

        FROM LG_011_BNCREPAYTR 
        WHERE TRANSTYPE = 0 
        GROUP BY PARENTREF) a 
INNER JOIN (SELECT
 LOGICALREF,
 PARENTREF,
 CREDITREF,
 DUEDATE,
 OPRDATE
 FROM LG_011_BNCREPAYTR
                WHERE TRANSTYPE = 0) b
ON a.PARENTREF=b.PARENTREF

LEFT OUTER JOIN (SELECT
 PARENTREF,
 SUM(TOTAL) AS ANAPARA,
 SUM(INTTOTAL) AS FAIZ,
 SUM(BSMVTOTAL) AS BSMV,
 SUM(KKDFTOTAL) AS KKDF,
 SUM(TOTAL+INTTOTAL+BSMVTOTAL+KKDFTOTAL) AS TAKSIT
        FROM LG_011_BNCREPAYTR 

Там что-то не так, потому что @query не получает все данные, и я не знаю, как я могу решить эту проблему. Буду очень признателен, если вы решите мою проблему!

Спасибо!

2 ответа

Решение

Как я решу эту проблему,

я) перед выполнением комментария (@query)

положить печать @query.

ii) Скопируйте весь обработанный скрипт в другое окно. Просто как-нибудь, как заставить его работать

iii) Включить эти изменения в динамический запрос.

iv) Вы уверены, что он отображается именно как [TL],[USD],[EUR].dOES, ЭТОТ столбцы существуют в таблицах, потому что вы используете псевдоним, такой как col6 [VADE], ' + @cols + '

Допустимо использовать "([sql1]) UNION ([sql2])" вместо "[sql1] UNION [sql2]". Это может помочь в изоляции проблемы. Без этого мне было трудно убедиться, что () соответствует в моем редакторе.

Другие вопросы по тегам