Set variable from user selection in SQL Server

心不动则不痛 提交于 2019-12-11 11:36:29

问题


I am beginner in SQL Server

My query in SAP B1 is

  DECLARE @FROMDATE AS DATETIME
  SET @FROMDATE= [%0]

  DECLARE @TODATE AS DATETIME
  SET @TODATE= [%1]

  DECLARE @ACCNUM AS NVARCHAR(100)
  SET @ACCNUM= [%2]

get the account name, number for every transaction of an account

   SELECT 
   T4.[ACCOUNT] AS 'A/C NUM',
   T4.[ACCTNAME] AS 'A/C NAME',
   T4.[TransId] AS 'KEY',

   SUM(VEL_DB) AS 'VEL DB',
   SUM(VEL_CR) AS 'VEL CR',

   SUM(DEF_DB) AS 'DEF_DB',
   SUM(DEF_CR) AS 'DEF CR',
   T4.[LINEMEMO],
   T1.[U_Naaration]


   FROM OJDT T1 

for every transaction in an account depending on the ocrcode2 credits and debits are calculated

   INNER JOIN 
      (
     SELECT T2.[TRANSID],T2.[ACCOUNT],T3.[ACCTNAME],T2.[LINEMEMO],

     case
     when T2.[OcrCode2]='VEL'
     THEN
       (T2.[Debit]) 
     ELSE
       NULL
     END as VEL_DB,

    case
    when T2.[OcrCode2]='VEL'
    THEN
     (T2.[CREDIT]) 
    ELSE
     NULL
    END as VEL_CR,

   case
   when T2.[OcrCode2]='' OR T2.[OCRCODE2] IS NULL
   THEN
     (T2.[Debit]) 
   ELSE
     NULL
   END as DEF_DB,

   case
   when T2.[OcrCode2]='' OR T2.[OCRCODE2]IS NULL
   THEN
       (T2.[CREDIT]) 
   ELSE
     NULL
   END as DEF_CR


   FROM JDT1 T2 
      INNER JOIN OACT T3 ON T3.[ACCTCODE]=T2.[ACCOUNT]
    where T2.[DUEDATE]>=@FROMDATE AND T2.[DUEDATE]<=@TODATE ) 
    T4 ON T4.TRANSID = T1.TRANSID AND T4.[ACCOUNT]=@ACCNUM


  GROUP BY T4.[TransId] ,T1.[U_Naaration],T4.[ACCTNAME],T4.[ACCOUNT],T4.[LINEMEMO]

   FOR BROWSE

I'm getting the error

must select a table to select from


回答1:


As per the correct answer by Petr Verner here, you may need to rewrite your query to avoid using a subquery.

The answer also goes on to suggest options:

  1. Embed the query into a stored procedure and call that SP instead.

  2. Use a view. (You could use it either for the subquery part or for the entire query).

  3. Store the results of a subquery into a table variable (or into a temporary table), and then use the saved result set in the main query.



来源:https://stackoverflow.com/questions/11342333/set-variable-from-user-selection-in-sql-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!