RE: Table Variable error in a query

Dear Readers, I am getting this error below when I create the table variable . Any ideas where I could be going wrong...
Use GG_TS
GO
--Using table variable
Declare @customerscount table
(firstname char(30),
 totals int,
 customerNumber int)
Insert @customerscount
Select
      Customers.firstname,
      Count(*) as 'Totals',
      Orders.CustomerNumber
FROM
     Customers join orders ON
     customers.customernumber = orders.customernumber
Group BY
      customers.firstname,orders.customernumber
The error I am getting is below:
Incorrect syntax near the keyword 'table'.
Thanks so much!
SQL 75

No, Now it's giving me a different error. Below is the error: By the way I am running this in SQL server 2012
under tempDB as it is a table variable.
Msg 208, Level 16, State 1, Line 6
Invalid object name 'Customers'.
Below is my Query:
Declare @customerscount table
(firstname char(30),
 totals int,
 customerNumber int)
Insert @customerscount
Select
      Customers.firstname,
      Count(*) as 'Totals',
      Orders.CustomerNumber
FROM
     Customers join orders ON
     customers.customernumber = orders.customernumber
Group BY
      customers.firstname,orders.customernumber
Thank-you
SQL 75
No need to run this in tempdb
You can run this in your database itself ie database where tables customers, orders etc exist and table variable gets created in tempdb itself
The reason for your error is because it cant find the tables in the tempdb database
So run the query in your own database
Otherwise you need to change it as below if you stiil want this to be executed in tempdb
Declare @customerscount table
(firstname char(30),
totals int,
customerNumber int)
Insert @customerscount
Select
c.firstname,
Count(*) as 'Totals',
o.CustomerNumber
FROM
<yourdbname>.dbo.Customers c join <yourdbname>.dbo.orders o ON
c.customernumber = o.customernumber
Group BY
c.firstname,o.customernumber
 assuming dbo is your default schema
Please Mark This As Answer if it solved your issue
Please Mark This As Helpful if it helps to solve your issue
Visakh
My MSDN Page
My Personal Blog
My Facebook Page

Similar Messages

  • Query in SQL 2008R2 error Msg 1087, Level 15, State 2, Line 31 Must declare the table variable

    Hello Experts, 
    Can You help me; I get the follwing error in my query
    Msg 1087, Level 15, State 2, Line 31
    Must declare the table variable "@ASE_SUBART_GROEP".
    the @ASE_SUBART_GROEP is a self-defined table in this SQL environment.
    Maybe you know the error or the missing part
    Thanks in advance, Jos Dielemans

    I'm not familiar with SAP Business One unfortunately, so can only be of limited help here. But I'm going to guess that @ASE_SUBART_GROEP is a table variable passed to a stored procedure and is defined and passed down by the application, so you won't
    be able to copy-paste this code directly into management studio and get it to work.
    You could remove the join to return *all* records. Although the dataset might be very big
    SELECT T0.CardCode AS 'Klantnr'
    ,T0.CardName AS 'Klantnaam'
    ,T4.GroupName AS 'Klantgroep'
    ,T9.Descr AS 'Merknaam'
    ,T5.SlpName AS 'Verkoper'
    ,T3.MailCity AS 'Leverplaats'
    ,T7.NAME AS 'Leverland'
    ,T3.City AS 'Factuurplaats'
    ,T7.NAME AS 'Factuurland'
    ,T0.DocNum AS 'Documentnr'
    ,T0.DocDate AS 'Datum'
    ,Cast((Datepart(Year, T0.DocDate)) AS VARCHAR) AS 'Jaar'
    ,RIGHT('00' + CAST(DATEPART(MONTH, T0.DocDate) AS VARCHAR(2)), 2) AS 'Maand'
    ,(Cast((Datepart(Year, T0.DocDate)) AS VARCHAR) + '-' + RIGHT('00' + CAST(DATEPART(MONTH, T0.DocDate) AS VARCHAR(2)), 2)) AS 'Periode'
    ,T1.ItemCode AS 'Artikelnr'
    ,T2.ItemName AS 'Artikelnaam'
    ,T1.Quantity AS 'Aantal VEH'
    ,T2.SVolume AS 'Aantal EH per VEH'
    ,(T1.Quantity * T2.SVolume) AS 'Aantal EH'
    ,T8.UnitName AS 'EH-Naam'
    ,T6.ItmsGrpNam AS 'Artikelgroep'
    ,T2.U_ItemGrp AS 'Hoofdgroep'
    ,T10.NAME AS 'Subgroep'
    ,T1.CogsAcct AS 'Kostpr.rek.'
    ,T1.AcctCode AS 'Opbrengstrek.'
    ,T1.LineTotal AS 'BrutoOmzet'
    ,T0.DiscPrcnt AS 'Korting'
    ,(+ T1.LineTotal * (100 - T0.DiscPrcnt) / 100) AS 'NettoOmzet'
    FROM dbo.OINV T0
    INNER JOIN dbo.INV1 T1 ON T0.DocEntry = T1.DocEntry
    INNER JOIN OITM T2 ON T1.ItemCode = T2.ItemCode
    INNER JOIN OCRD T3 ON T0.CardCode = T3.CardCode
    INNER JOIN OCRG T4 ON T3.GroupCode = T4.Groupcode
    INNER JOIN OSLP T5 ON T3.SlpCode = T5.SlpCode
    INNER JOIN OITB T6 ON T2.ItmsGrpCod = T6.ItmsGrpCod
    INNER JOIN OCRY T7 ON T3.Country = T7.Code
    LEFT OUTER JOIN OLGT T8 ON T2.SVolUnit = T8.UnitCode
    LEFT OUTER JOIN UFD1 T9 ON T3.U_ZPgroep = T9.FldValue
    AND TableID = 'OCRD'
    AND FieldID = 2
    --LEFT OUTER JOIN @ASE_SUBART_GROEP T10 ON T2.U_ASE_SUB_ARTGROEP = T10.Code
    WHERE T0.DocDate >= '20120101'
    AND T0.Canceled = 'N'
    UNION ALL
    SELECT T0.CardCode AS 'Klantnr'
    ,T0.CardName AS 'Klantnaam'
    ,T4.GroupName AS 'Klantgroep'
    ,T9.Descr AS 'Merknaam'
    ,T5.SlpName AS 'Verkoper'
    ,T3.MailCity AS 'Leverplaats'
    ,T7.NAME AS 'Leverland'
    ,T3.City AS 'Factuurplaats'
    ,T7.NAME AS 'Factuurland'
    ,T0.DocNum AS 'Documentnr'
    ,T0.DocDate AS 'Datum'
    ,Cast((Datepart(Year, T0.DocDate)) AS VARCHAR) AS 'Jaar'
    ,RIGHT('00' + CAST(DATEPART(MONTH, T0.DocDate) AS VARCHAR(2)), 2) AS 'Maand'
    ,(Cast((Datepart(Year, T0.DocDate)) AS VARCHAR) + '-' + RIGHT('00' + CAST(DATEPART(MONTH, T0.DocDate) AS VARCHAR(2)), 2)) AS 'Periode'
    ,T1.ItemCode AS 'Artikelnr'
    ,T2.ItemName AS 'Artikelnaam'
    ,- T1.Quantity AS 'Aantal VEH'
    ,T2.SVolume AS 'Aantal EH per VEH'
    ,(- T1.Quantity * T2.SVolume) AS 'aantal EH'
    ,T8.UnitName AS 'EH-Naam'
    ,T6.ItmsGrpNam AS 'Artikelgroep'
    ,T2.U_ItemGrp AS 'Hoofdgroep'
    ,T10.NAME AS 'Subgroep'
    ,T1.CogsAcct AS 'Kostpr.rek.'
    ,T1.AcctCode AS 'Opbrengstrek.'
    ,- T1.LineTotal AS 'BrutoOmzet'
    ,T0.DiscPrcnt AS 'Korting'
    ,(+ T1.LineTotal * (100 - T0.DiscPrcnt) / 100) AS 'NettoOmzet'
    FROM dbo.ORIN T0
    INNER JOIN dbo.RIN1 T1 ON T0.DocEntry = T1.DocEntry
    INNER JOIN OITM T2 ON T1.ItemCode = T2.ItemCode
    INNER JOIN OCRD T3 ON T0.CardCode = T3.CardCode
    INNER JOIN OCRG T4 ON T3.GroupCode = T4.Groupcode
    INNER JOIN OSLP T5 ON T3.SlpCode = T5.SlpCode
    INNER JOIN OITB T6 ON T2.ItmsGrpCod = T6.ItmsGrpCod
    INNER JOIN OCRY T7 ON T3.Country = T7.Code
    LEFT OUTER JOIN OLGT T8 ON T2.SVolUnit = T8.UnitCode
    LEFT OUTER JOIN UFD1 T9 ON T3.U_ZPgroep = T9.FldValue
    AND TableID = 'OCRD'
    AND FieldID = 2
    --LEFT OUTER JOIN @ASE_SUBART_GROEP T10 ON T2.U_ASE_SUB_ARTGROEP = T10.Code
    WHERE T0.DocDate >= '20120101'
    AND T0.Canceled = 'N'
    ORDER BY T0.CardCode
    The join to the table variable has been commented out above, so the code should run. After that you might want to update the WHERE clause to include only particular sub-groups

  • ERROR BRAIN (738): Variable 0P_KEYDT not in query

    Hi all,
    Can anyone help with the following error that i am getting while executing a query
    ERROR BRAIN (738): Variable 0P_KEYDT not in query
    Regards,
    P

    Make sure you still have the variable in the query. You did not delete it by mistake. Error is it self says that it can not find that 0P_KEYDT in the query. YOu can also try removing and adding it again.
    Sometimes the order of making variable matters when you have dependency.
    - Danny

  • Error when executing query without passing variable selection

    Hi Gurus
    I am getting an error while executing a query with out passing values for variables
    When executing the query by passing the filter values report returns the data
    When executing the query with out passing variable selections the error message is
    Unknown error in SQL interface
    Error reading the data of Info Provider ZCRM_O08
    Error while reading data; navigation possible
    System error in program SSAPLRS_EXCEPTION and form
    RS_EXCEPTION_TO_MESSAGE
    No Data Available
    can any one please help me in resolving this
    Thank you

    Hi Srini
    Thanks for your quick response
    When i am executing the query with selection it is returning the data
    giving error when executing with out passing the selection
    is there any other cause for this problem
    like any particular info object causes this sort of problem
    Thank you

  • Bind variable error while adding dynamic where clause to VO query

    hi
    i have extended a VO and in the VOImpl i have written the following code
    public class HzPuiClassificationListVOExImpl extends HzPuiClassificationListVOImpl
    public void initQuery(String partyId, String s1, String classCode)
    /* Logging Code*/
    if(this.isLoggingEnabled(OAFwkConstants.PROCEDURE))
    {this.writeDiagnostics(this," > initQuery() , partyId ="+partyId+" , s1 ="+s1+", classCode="+classCode,OAFwkConstants.PROCEDURE);}
    setWhereClauseParams(null);
    setWhereClauseParam(0, classCode);
    setWhereClauseParam(1, classCode);
    setWhereClauseParam(2, partyId);
    String query = super.getQuery();
    * Check if the whereClause is already present
    if(query!=null && query.toUpperCase().indexOf("AAAAA") == -1)
    OAApplicationModule am = (OAApplicationModule)this.getApplicationModule();
    OADBTransaction oadbTxn = am.getOADBTransaction();
    String whereClause = "   class_category IN ("+
    *" SELECT flv.lookup_code"+*
    *" FROM fnd_lookup_values flv, fnd_lookup_values_dfv dfv"+*
    *" WHERE flv.rowid = dfv.row_id"+*
    *" AND flv.lookup_type = 'XXXXX'"+*
    *" AND dfv.context_value = flv.lookup_type"+*
    *" AND dfv.oco_enabled = 'Y' "+*
    this.addWhereClause(whereClause);
    this.executeQuery();
    * This is the default constructor (do not remove)
    public HzPuiClassificationListVOExImpl()
    when i run the page i get this error
    java.sql.SQLException: Missing IN or OUT parameter at index:: 2
    the original vo query below has 3 bind variables
    SELECT *
    FROM (SELECT *
    FROM (SELECT cc.class_category
    ,l.meaning
    FROM hz_class_categories cc
    ,fnd_lookup_types_vl l
    WHERE cc.class_category = l.lookup_type
    AND l.view_application_id = 222
    AND EXISTS (
    SELECT NULL
    FROM hz_code_assignments ca
    WHERE ca.owner_table_name = 'HZ_CLASS_CATEGORIES'
    AND ca.owner_table_id IS NULL
    AND ca.owner_table_key_1 = cc.class_category
    AND ca.class_category = 'CLASS_CATEGORY_GROUP'
    AND ca.class_code = :1
    AND NVL (ca.status, 'A') = 'A'
    AND SYSDATE BETWEEN ca.start_date_active AND NVL (ca.end_date_active, SYSDATE + 1))
    UNION ALL
    SELECT cc.class_category
    ,l.meaning
    FROM hz_class_categories cc
    ,fnd_lookup_types_vl l
    WHERE cc.class_category = l.lookup_type
    AND l.view_application_id = 222
    AND 'INDUSTRIAL_GROUP' <> :2
    AND NOT EXISTS (
    SELECT NULL
    FROM hz_code_assignments ca
    WHERE ca.owner_table_name = 'HZ_CLASS_CATEGORIES'
    AND ca.owner_table_id IS NULL
    AND ca.owner_table_key_1 = cc.class_category
    AND ca.class_category = 'CLASS_CATEGORY_GROUP'
    AND NVL (ca.status, 'A') = 'A'
    AND SYSDATE BETWEEN ca.start_date_active AND NVL (ca.end_date_active, SYSDATE + 1))
    AND hz_classification_v2pub.is_valid_category ('HZ_PARTIES'
    ,cc.class_category
    ,:3) = 'T') a
    WHERE EXISTS (
    SELECT NULL
    FROM hz_class_code_denorm
    WHERE class_category = a.class_category
    AND TRUNC (SYSDATE) BETWEEN NVL (start_date_active, TRUNC (SYSDATE)) AND NVL (end_date_active, TRUNC (SYSDATE))
    AND enabled_flag = 'Y'
    AND LANGUAGE = USERENV ('LANG'))) qrslt
    A similar error was discussed at this link but it did not give final solution
    [http://kr.forums.oracle.com/forums/thread.jspa?threadID=618451]
    help me to solve this issue..
    Thanks,
    Varun
    Edited by: user10707840 on May 19, 2009 7:18 AM

    its not the AM code .. its the code in VOImpl...
    the same code is working in 11i but when its migrated to R12 its giving this error..
    The original seeded VO query in 11i contains the same bind variable :1 at three places
    SELECT * FROM (select class_category, meaning from hz_class_categories, fnd_lookup_types_vl l where hz_class_categories.class_category = l.lookup_type and l.view_application_id = 222 and class_category in (select owner_table_key_1 from hz_code_assignments ca where ca.owner_table_name = 'HZ_CLASS_CATEGORIES' and ca.owner_table_id is null and ca.class_category = 'CLASS_CATEGORY_GROUP' and ca.class_code = :1 and nvl(ca.status, 'A') = 'A' and sysdate between ca.start_date_active and nvl(ca.end_date_active, sysdate+1)) union all select cc.class_category , meaning from hz_class_categories cc, fnd_lookup_types_vl l, hz_class_category_uses cu where cc.CLASS_CATEGORY = cu.class_category AND ( UPPER(CU.ADDITIONAL_WHERE_CLAUSE) LIKE decode(:1, 'ORG_GROUP','%PARTY_TYPE%ORGANIZATION%', 'PERSON_GROUP', '%PARTY_TYPE%PERSON%', '%') or CU.ADDITIONAL_WHERE_CLAUSE IS NULL or UPPER(CU.ADDITIONAL_WHERE_CLAUSE) LIKE '%WHERE 1=1%' ) and cu.owner_table = 'HZ_PARTIES' and cc.class_category = l.lookup_type and l.view_application_id = 222 and cc.class_category not in (select owner_table_key_1 from hz_code_assignments hca where hca.owner_table_name = 'HZ_CLASS_CATEGORIES' and hca.owner_table_id is null and hca.class_category = 'CLASS_CATEGORY_GROUP' and nvl(hca.status, 'A') = 'A' and sysdate between hca.start_date_active and nvl(hca.end_date_active, sysdate+1)) and cc.class_category not in ( 'RELATIONSHIP_TYPE_GROUP', 'CLASS_CATEGORY_GROUP') and 'INDUSTRIAL_GROUP' <> :1) QRSLT ORDER BY meaning
    the code working in 11i had only one setWhereClauseParam line i.e. setWhereClauseParam(0, classCode);
    when i ran the same code in R12 it errd out..
    I checked the original R12 query... it has 3 bind variables :1 , :2 and :3 ... so i added 2 more setWhereClauseParam statements
    setWhereClauseParam(1, classCode);
    setWhereClauseParam(2, partyId);
    but still its giving the same error
    ORIGINAL R12 query already posted above...

  • Error: None of the fact tables are compatible with the query request

    Hi experts,
    I have one confirm dimension D1 and other two fact table F1 and F2 (F1 and F2 are connected to D1)
    when i create a report from D1 and F1 the report is running fine. But pull the column from F2 also in this report i am getting the following error
    None of the fact tables are compatible with the query request Code Combinations
    please suggest on the same.
    Regards,
    S

    Hi
    i have done the content level setting in each of the table, D1,F1 and F2(LTS), now i am getting the following error..
    State: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 15018] Incorrectly defined logical table source (for fact table Gl Sets Of Books) does not contain mapping for [Code Combinations.Code Combinations.Affiliate, GL Balances.GL Balances.Currency Code, GL Balances.GL Balances.PTD_Balance, Gl Sets Of Books.Gl Sets Of Books .SoB Name]. (HY000)
    Gl Balances : D1
    Code Commbination: F1
    Gl Sets Of Books : F2
    I have checked the joins in physical and BMM layer..all are fine..

  • "None of the fact tables are compatible with the query request " error

    I've got a situation where I have two facts(Fact_1, Fact_2) and three dimensions(dim_1,dim_2,dim_3) in 1 subject area. I've got dimension hierarchies setup for all the dimension tables.
    Dim_1 is one to many to Fact_1
    Dim_2 is one to many to Fact_2
    Dim_3 is one to many to both Fact_1 and Fact_2
    I've set up the content levels for the LTS for the Facts so that they are the lowest grain for dimensions they join to and the grand total grain for dimensions they do not join to.
    My rpd is consistent. When I run a report using an attribute from Dim_3 and Dim_1 or Dim_3 and Dim_2, the report comes back fine.
    But if I try to run a report using all three Dim tables, I get an error and the message "None of the fact tables are compatible with the query request ".
    First of all, is it possible to make a report using all three dimensions?
    Second, what's the best way to trouble shoot this error? Why are none of the fact tables compatible? I thought as long as the aggregation levels were set to grand total for non-shared dimensions, Answers would be able to create the report properly.
    Any advise would be greatly appreciated.
    Thanks!
    -Joe

    OBIEE is looking for a fact that can link ALL the dimensions together. This is also known as the implicit fact ... you don't have a fact that can relate all the dimensions - you have 2 facts that together they can. Perhaps you need to great a single logical fact that has both LTS for your physical facts and try it that way.
    Then you'd have Dim1, Dim 2, Dim3 all being able to join to Fact1 (which is made of physical facts 1 & 2).

  • Internal table with same variable and one select query

    Hi,
    I am a new bee here with may be a silly question.
    I have a internal table as below.
    DATA: BEGIN OF IT_ORDERDETAILS OCCURS 0,
            VBELN LIKE VBAK-VBELN,        "Order number
            BSTNK LIKE VBAK-BSTNK,        "customer PO
            ERDAT LIKE VBAK-ERDAT,        " Order created date
            MATNR LIKE VBAP-MATNR,        "Sales order line item
            KWMENG LIKE VBAP-KWMENG,      "Quantity
            D_VBELN like likp-vbeln,      " delivery no
            POSNR like lips-posnr,        " delivery item
            KUNNR LIKE LIKP-KUNNR,        "ship quantity
      END OF IT_ORDERDETAILS.
    Where VBELN field is in VBAK and LIKP table.
    VBELN in VBAK table = order #
    VBELN in LIKP table is = Delivery #
    I want to use join to fetch data in single select query.
    Below is the select query
    SELECT VBAK~VBELN
            VBAK~BSTNK
            VBAK~ERDAT
            VBAP~MATNR
            VBAP~KWMENG
            likp~vbeln
            lips~posnr
            LIPS~VGBEL
          INTO (IT_ORDERDETAILSvbak, IT_ORDERDETAILSbstnk,     IT_ORDERDETAILSerdat, IT_ORDERDETAILSmatnr, IT_ORDERDETAILSkwmeng, IT_ORDERDETAILSd_vbeln,IT_ORDERDETAILSposnr, IT_ORDERDETAILSkunnr)
    FROM VBAK left outer JOIN VBAP ON ( VBAKVBELN = VBAPVBELN )
    left outer JOIN LIPS ON ( VBAKVBELN = LIPSVGBEL )
      join LIKP on ( LIPSVBELN = LIKPVBELN )
    WHERE VBAK~ERDAT IN CR_DATE.
    I am getting error in the query.
    Please suggest.
    Thanks,
    Rajesh

    Hi rajesh.nayakbola,
    although this is not quite the right place for this, let me give you some notes:
    1. Code should be
    formatted as code
    by markin it with mouse and use above &lt;&gt; button.
    2. Internal tables shoult not be declared using OCCURS clause - this is last century style
    3. Internal tables do not need and should not have a header line, they should use TYPES for declaration
    4. Data should not be declared using LIKE: If they refer to dictionary TYPES, use TYPE. LIKE is only mandatory for data objects declared in your program, i.e. DATA IT_some_ORDERDETAILS like IT_ORDERDETAILS.
    5. If you get an error here, never write "I am getting error" but copy and paste the error message fully.
    - The fields in brackets in  the INTO clause never have ~ character, there is no IT_ORDERDETAILS~vbak, only IT_ORDERDETAILS-vbeln
    It could be something like this:
    TYPES:
      BEGIN OF TY_ORDERDETAILS,
      VBELN TYPE VBAK-VBELN, "Order number
      BSTNK TYPE VBAK-BSTNK, "customer PO
      ERDAT TYPE VBAK-ERDAT, " Order created date
      MATNR TYPE VBAP-MATNR, "Sales order line item
      KWMENG TYPE VBAP-KWMENG, "Quantity
      D_VBELN TYPE likp-vbeln, " delivery no
      POSNR TYPE lips-posnr, " delivery item
      KUNNR TYPE LIKP-KUNNR, "ship quantity
    END OF TY_ORDERDETAILS.
    DATA:
      IT_ORDERDETAILS TYPE TABLE OF TY_ORDERDETAILS.
    SELECT VBAK~VBELN
      VBAK~BSTNK
      VBAK~ERDAT
      VBAP~MATNR
      VBAP~KWMENG 
      likp~vbeln AS D_VBELN
      lips~posnr
      LIKP~KUNNR
    INTO CORRSPONDING FIELDS OF TABLE IT_ORDERDETAILS
    FROM VBAK left outer JOIN VBAP ON ( VBAK~VBELN = VBAP~VBELN )
      left outer JOIN LIPS ON ( VBAK~VBELN = LIPS~VGBEL )
      join LIKP on ( LIPS~VBELN = LIKP~VBELN )
    WHERE VBAK~ERDAT IN CR_DATE.
    Regards,
    Clemens

  • Table variable query optimisation

    I have a table variable which (sometimes) needs to contain a couple of thousand rows, this slews the execution plan. This is fixed by DBCC TRACEON(2453) which causes the
    rows in the table variable to be estimated properly, this requires sysadmin rights which I am reluctant to grant to other than this stored proc. The proc is excuted by most users with SQL authentication. I've tried with exec as 'NT AUTHORITY\SYSTEM' but that
    does not seem to be recognized as I'm using sql authentication. Cant use a temp table as this breaks asp net Linq which is user to wrap the stored procedure.
    Suggestions please? Is there another way to tell the proc to count the row in a table variable? Is there a tight scripted way to grant
    sysadmin rights to just this stored proc across a number of databases and servers?

    Hi Erland, I'm feeling particularly dumb at the moment... I read your article and each step seems clear. so I then tried to put together a script to create a certificate, create a logon, create a (SQL) user, create a proc to run as that user and test. My
    dismal attempt is below.
    USE master
    go
    -- Create a test login and test database
    CREATE LOGIN testuser WITH PASSWORD = 'CeRT=0=TeST'
    CREATE DATABASE certtest
    go
    -- Move to the test database.
    USE certtest
    go
    -- Create the test user.
    CREATE USER testuser
    go
    -- Create the test table and add some data.
    CREATE TABLE testtbl (a int NOT NULL,
                          b int NOT NULL)
    INSERT testtbl (a, b) VALUES (47, 11)
    go
    -- Create the certificate.
    CREATE CERTIFICATE TraceOnCert
       ENCRYPTION BY PASSWORD = 'All you need is love'
       WITH SUBJECT = 'Certificate for TraceOnProc',
       START_DATE = '20020101', EXPIRY_DATE = '20200101'
    go
    -- Create the login
    CREATE LOGIN TraceOnLogin WITH PASSWORD = 'CeRT=0=TeST'
    GO
    --create user link to login
    IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'TraceOnUser')
        CREATE USER TraceOnUser FOR LOGIN TraceOnLogin
    --give login sysadmin rights
    EXEC master..sp_addsrvrolemember @loginame = N'TraceOnLogin', @rolename = N'sysadmin'
    go
    GRANT SELECT ON testtbl TO TraceOnUser
    go
    -- Create two test stored procedures, and grant permission.
    CREATE PROCEDURE unsigned_sp AS
        DBCC TRACEON(2453)
       SELECT SYSTEM_USER, USER, name, type, usage FROM sys.user_token
       EXEC ('SELECT a, b FROM testtbl')
       DBCC TRACEOFF(2453)
    go
    CREATE PROCEDURE TraceOnProc WITH EXECUTE AS 'TraceOnUser' AS
        DBCC TRACEON(2453)
       SELECT SYSTEM_USER, USER, name, type, usage FROM sys.user_token
       EXEC ('SELECT a, b FROM testtbl')
       DBCC TRACEOFF(2453)
       -- EXEC unsigned_sp
    go
    GRANT EXECUTE ON TraceOnProc TO public
    GRANT EXECUTE ON unsigned_sp TO public
    go
    go
    -- Run as the test user, to actually see that this works.
    EXECUTE AS USER = 'testuser'
    go
    -- First run the unsigned procedure. This gives a permission error.
    EXEC unsigned_sp
    go
    -- Then run the signed procedure. Now we get the data back.
    EXEC TraceOnProc
    go
    -- Become ourselves again.
    REVERT
    go
    -- Clean up
    USE master
    DROP DATABASE certtest
    DROP LOGIN testuser
    DROP LOGIN TraceOnLogin

  • Fixing this Table Variable Query

    Please assist me to correct this syntax for this Table Variable Question below.   
    /* Create a table variable with Departure City and State in 2 different columns along 
    with Flight Destination City and Ontime. */
    DECLARE @NTable TABLE (FlightDepartureCity varchar(50), FlightDepartureCity1 varchar(50),FlightDestinationCity varchar(50), [Ontime] INT)
    INSERT INTO @NTable 
    SELECT Left(FlightDepartureCity,CHARINDEX('-',FlightDepartureCity)-1) as City,
    RIGHT(FlightDepartureCity,LEN(FlightDepartureCity) - CHARINDEX('-',FlightDepartureCity)) as FirstName,
    FlightDestinationCity, Ontime
    FROM Flights
    SELECT Left(FlightDepartureCity,CHARINDEX('-',FlightDepartureCity)-1),
        RIGHT(FlightDepartureCity,LEN(FlightDepartureCity) - CHARINDEX('-',FlightDepartureCity))  , 
        FlightDestinationCity, Ontime FROM @NTable

    Disregard I figured it out
    DECLARE @NTable TABLE (FlightDepartureCity varchar(50), FlightDepartureCity1 varchar(50),FlightDestinationCity varchar(50), [Ontime] INT)
    INSERT INTO @NTable 
    SELECT Left(FlightDepartureCity,CHARINDEX('-',FlightDepartureCity)-1) as City,
    RIGHT(FlightDepartureCity,LEN(FlightDepartureCity) - CHARINDEX('-',FlightDepartureCity)) as FirstName,
    FlightDestinationCity, Ontime
    FROM Flights
    SELECT * from @NTable

  • How to include variable on block's query

    I have a block where I fetch data using Query with sub-querry on Query data source name. The problem is that I need to put a variable in a sub-query, but it returned error: ORA-01008 not all variables bound. I'm retrieving multiple records here.
    SELECT DISTINCT --fields
    FROM table1 a, table2 b, table3 c, table4 d
    WHERE a.line_cd = b.line_cd
    AND a.line_cd = 21
    --other conditions
    AND a.clm_seq_no = 7100003
    AND d.eff_dt = (SELECT MAX(eff_dt)
              FROM table4
              WHERE 1=1
              AND srvc_code = a.srvc_code
              AND line_cd = a.line_cd
              AND sched_no = a.sched_no
              AND cover_code = a.cover_code
              AND eff_dt <= :global.variable --problem
    )

    Thanks for your replies.
    Query Data source typy = Table, I also tried using package that serves as handler of global variable (variables.eff_dt) but it gives me error (cannot perform query).
    ( SELECT * FROM (SELECT DISTINCT a.claimant_seq, a.expense_title title,
    NVL(c.max_chrg, 0) max_chrg, NVL(c.min_chrg, 0) min_chrg, DECODE(tran_type, 2,
    a.amount * -1, a.amount) amnt, a.line_cd, a.subline_cd, a.iss_cd, a.clm_yy,
    a.clm_seq_no, a.item_no, a.peril_cd, a.sched_no, a.cover_code, a.srvc_code,
    a.srvc_dtl_code, NVL(a.days, 0) no_days, c.no_days days, NVL(d.min_chrg, 0) MIN,
    NVL(d.max_chrg, 0) MAX, a.dtls_seq, a.limit_amt, a.ctpl_amt, a.excess_amt
    FROM VTPLBI_DTLS a, POL_COVERAGE b, POL_SRVC_DTLS c, pol_services d
    WHERE a.line_cd = b.line_cd
    AND a.sched_no = b.sched_no
    AND a.cover_code = b.cover_code
    AND b.line_cd = d.line_cd
    AND b.sched_no = d.sched_no
    AND b.cover_code = d.cover_code
    AND a.srvc_code = d.srvc_code
    AND a.srvc_code = c.srvc_code(+)
    AND a.line_cd = c.line_cd(+)
    AND a.sched_no = c.sched_no(+)
    AND a.cover_code = c.cover_code(+)
    AND a.srvc_dtl_code = c.srvc_dtl_code(+)
    AND d.eff_dt = (SELECT MAX(eff_dt) --wency05082007
              FROM POL_SERVICES
              WHERE 1=1
              AND srvc_code = a.srvc_code
              AND line_cd = a.line_cd
              AND sched_no = a.sched_no
              AND cover_code = a.cover_code
              AND eff_dt <= variables.v_eff_dt --here is the problem
    UNION SELECT DISTINCT a.claimant_seq, a.expense_title, 0, 0, DECODE(tran_type,
    2, a.amount * -1, a.amount) amnt, a.line_cd, a.subline_cd, a.iss_cd, a.clm_yy,
    a.clm_seq_no, a.item_no, a.peril_cd, a.sched_no, a.cover_code, a.srvc_code,
    a.srvc_dtl_code, NVL(a.days, 0) no_days, 0, 0, 0, a.dtls_seq, a.limit_amt,
    a.ctpl_amt, a.excess_amt
    FROM VTPLBI_DTLS a
    WHERE (a.sched_no = 2 or a.sched_no is null) )
    ORDER BY dtls_seq ) comp_dtl
    Message was edited by:
    Wency

  • Java.sql.SQLException: ORA-00933: error when  executing query

    Hello,
    I am trying to execute the following query from a jsp page.
    String sqlUpdate ="UPDATE table_name SET name ='"+name+"', description='"+description+"', proj_link='" projlink"', active='" active"',sort_order='" order"',image='" image"',category='" category"', technology='" technology "' WHERE id="+id+" ";
    stmt.executeQuery(sqlUpdate);
    I get the follwoing error java.sql.SQLException: ORA-00933: SQL command not properly ended
    When I omit "description" from the query it executes fine. But when I place it back into the query I get the above error. The table is in Oracle database and the datatype of description id varchar2(4000). I declared all the variables used in the query, I then assigned values caught from the form and then am trying to update the form varibles in the table.
    Thanks,
    Nikky128

    Nikky128 wrote:
    Hello,
    I am trying to execute the following query from a jsp page.There's a big part of your problem. You shouldn't be doing database stuff in JSPs. If you must, you should be using JSTL and its <sql> tags.
    String sqlUpdate ="UPDATE table_name SET name ='"+name+"', description='"+description+"', proj_link='" projlink"', active='" active"',sort_order='" order"',image='" image"',category='" category"', technology='" technology "' WHERE id="+id+" ";Not using PreparedStatement here is just a silly noob error.
    When I omit "description" from the query it executes fine. But when I place it back into the query I get the above error. The table is in Oracle database and the datatype of description id varchar2(4000). I declared all the variables used in the query, I then assigned values caught from the form and then am trying to update the form varibles in the table.Probably a single or double quote that you can't see. PreparedStatement will eliminate that problem.
    %

  • Using Table Variables MSSQL with xMII 11.5

    I was trying an experiment with a query today where instead of creating a temp table in SQL, I used the T-SQL table variable.  For a simple example: 
    DECLARE @ProductTotals TABLE
    (  ProductID int,   Revenue money)
    INSERT INTO @ProductTotals (ProductID, Revenue)
    SELECT ProductID, SUM(UnitPrice * Quantity)
    FROM [Order Details]
    GROUP BY ProductID
    SELECT *
    FROM  @ProductTotals
    Well, this works fine in SQL Query Analyzer , but not in xMII.  I get a message that says "no results returned from this query"    So you ask, "why not just use a temp table"  Well on the real application, the query can take up to 30 seconds to run, and I have the chance of having multiple users execute the same query in that time, in which my temp table will get stomped on creating an error.  So I thought of using table variables as a possible alternative to avoid this.  
    I have already figured a work around, I put this code into a stored procedure and call that.  I could also do a similar workaround using separate queries / BLS.  However, I'm curious why xMII wouldn't execute this in the first place, being that it worked fine in Query Analyzer against the exact same database.

    Doug,
    I tried on my box with the "sqljdbc.jar" from 11.08.2006 (German Dateformat dd.MM.yyyy) and works also.
    For my test I had using the following SQL-Statement:
    DECLARE @ProductTotals TABLE
    ( ProductCount int, ProductID int, Revenue money)
    INSERT @ProductTotals
    SELECT count(O.ProductID) as ProductCount, P.ProductID, SUM(O.UnitPrice * O.Quantity)
    FROM [Order Details] O
    INNER JOIN Products P
    ON O.ProductID = P.ProductID
    GROUP BY P.ProductID
    SELECT *
    FROM @ProductTotals
    Did you get a result back in MII only for the SELECT statement
    SELECT count(O.ProductID) as ProductCount, P.ProductID, SUM(O.UnitPrice * O.Quantity)
    FROM [Order Details] O
    INNER JOIN Products P
    ON O.ProductID = P.ProductID
    GROUP BY P.ProductID
    ? My opinion is, that your select brings nothing back.
    Regards
    Pedro

  • Insert Excel information to Access Table, cf error

    I am trying to create a file upload that will allow me to use a .csv file, to insert the data into an access database. I have the code written, but right now, it's giving me an error and I can't figure out what I'm doing wrong, this is my first time doing this, so any and all help would be greatly appreciated.
    This is my code to read the .csv file.:
    <cftry>
    <cffile action="DELETE" file="#FORM.attachment_1#"/>
    <cfcatch>
    <!--- File delete error. --->
    </cfcatch>
    </cftry>
    <cfelse>
    <!--- no errors with the file upload so lets upload it--->
    <cffile action="upload"
                     filefield="attachment_1"
                     result="myResult"
                     accept = ""
                     destination="f:\websites\211562Fe3\uploads\"
                     nameconflict="Makeunique">
    <cfset svrFile = "#myResult.ServerDirectory#"&"\"&"#myResult.ServerFile#"/>
    <!--- get and read the CSV-TXT file --->
    <cffile action="read" file="#svrFile#" variable="csvfile">
    <!--- loop through the CSV-TXT file on line breaks and insert into database --->
    <cfloop index="index" list="#csvfile#" delimiters="#chr(10)##chr(13)#">
        <cfquery name="importcsv" datasource="#APPLICATION.dataSource#">
             INSERT INTO employees (siteID,empstatus,empfirstname,empmiddlename,emplastname,empnickname,emplocation,empgende r,empdob,empdoh,empee)
             VALUES
                      ('#listgetAt('#index#',1, ',')#',
                       '#listgetAt('#index#',2, ',')#',
                       '#listgetAt('#index#',3, ',')#',
                       '#listgetAt('#index#',4, ',')#',
                       '#listgetAt('#index#',5, ',')#',
                       '#listgetAt('#index#',6, ',')#',
                       '#listgetAt('#index#',7, ',')#',
                       '#listgetAt('#index#',8, ',')#',
                       '#listgetAt('#index#',9, ',')#',
                       '#listgetAt('#index#',10, ',')#',
                       '#listgetAt('#index#',11, ',')#'
       </cfquery>
    </cfloop>
    <cffile action="DELETE" file="#svrFile#"/>
    <!--- use a simple database query to check the results of the import - dumping query to screen --->
    <cfquery name="rscsvdemo" datasource="#APPLICATION.dataSource#">
             SELECT * FROM csvdemo
    </cfquery>
    <cfdump var="#employees#">
    </cfif>
    The error is in the insert query, I have all my columns named the same ad the database table and in the same order, I also formatted each cell in the .csv to be the same as the database.
    This is the error:
    Error Executing Database Query.
    [Macromedia][SequeLink JDBC Driver][ODBC Socket][Microsoft][ODBC  Microsoft Access Driver] Data type mismatch in criteria expression.
    The error occurred in  C:\websites\211562fe3\partners\cfm\csvUploadAction.cfm: line 60
    58 :                    '#listgetAt('#index#',9, ',')#',
    59 :                    '#listgetAt('#index#',10, ',')#',
    60 :                    '#listgetAt('#index#',11, ',')#' 
    61 :                   )
    62 :    </cfquery>
    Thank you

    I changed my code a little.. now I get an error about converting a date.. so I must be on the right track.... Can you help me straiten this out?
    This is my "new" code:
    <cftry>
    <cffile action="DELETE" file="#FORM.attachment_1#"/>
    <cfcatch>
    <!--- File delete error. --->
    </cfcatch>
    </cftry>
    <cfelse>
    <!--- no errors with the file upload so lets upload it--->
    <cffile action="upload"
                     filefield="attachment_1"
                     result="myResult"
                     accept = ""
                     destination="c:\websites\211562Fe3\uploads\"
                     nameconflict="Makeunique">
    <cfset svrFile = "#myResult.ServerDirectory#"&"\"&"#myResult.ServerFile#"/>
    <!--- get and read the CSV-TXT file --->
    <cffile action="read" file="#svrFile#" variable="csvfile">
    <!--- loop through the CSV-TXT file on line breaks and insert into database --->
    <cfloop index="i" list="#csvfile#" delimiters="#chr(10)##chr(13)#">
        <cfquery name="importcsv" datasource="#APPLICATION.dataSource#">
             INSERT INTO employees (siteID,empstatus,empfirstname,empmiddlename,emplastname,empnickname,emplocation,empgende r,empdob,empdoh,empee)
             VALUES
                      (<CFQUERYPARAM CFSQLTYPE="cf_sql_varchar" VALUE="#trim(listgetAt(i,1))#">,
                        <CFQUERYPARAM CFSQLTYPE="cf_sql_varchar" VALUE="#listgetAt(i,2)#">,
                        <CFQUERYPARAM CFSQLTYPE="cf_sql_varchar" VALUE="#listgetAt(i,3)#">,
                     <CFQUERYPARAM CFSQLTYPE="cf_sql_varchar" VALUE="#trim(listgetAt(i,4))#">,
                     <CFQUERYPARAM CFSQLTYPE="cf_sql_varchar" VALUE="#listgetAt(i,5)#">,
                     <CFQUERYPARAM CFSQLTYPE="cf_sql_varchar" VALUE="#listgetAt(i,6)#">,
                     <CFQUERYPARAM CFSQLTYPE="cf_sql_varchar" VALUE="#listgetAt(i,7)#">,
                     <CFQUERYPARAM CFSQLTYPE="cf_sql_varchar" VALUE="#listgetAt(i,8)#">,
                     <CFQUERYPARAM CFSQLTYPE="CF_SQL_DATE" VALUE="#listgetAt(i,9)#">,
                     <CFQUERYPARAM CFSQLTYPE="CF_SQL_DATE" VALUE="#listgetAt(i,9)#">,
                     <CFQUERYPARAM CFSQLTYPE="cf_sql_varchar" VALUE="#listgetAt(i,9)#">
       </cfquery>
    </cfloop>
    <cffile action="DELETE" file="#svrFile#"/>
    <!--- use a simple database query to check the results of the import - dumping query to screen --->
    <cfquery name="rscsvdemo" datasource="#APPLICATION.dataSource#">
             SELECT * FROM employees
    </cfquery>
    <cfdump var="#employees#">
    </cfif>
    I'm not sure it's totally correct.. but the error is different!
    This is the error:
    The cause of this output exception was that:  coldfusion.runtime.Cast$DateStringConversionException: The value empdob  cannot be converted to a date..
    The error occurred inf :\websites\211562fe3\partners\cfm\csvUploadAction.cfm: line 58
    56 :                  <CFQUERYPARAM CFSQLTYPE="cf_sql_varchar"  VALUE="#listgetAt(i,7)#">,
    57 :                  <CFQUERYPARAM CFSQLTYPE="cf_sql_varchar"  VALUE="#listgetAt(i,8)#">,
    58 :                  <CFQUERYPARAM CFSQLTYPE="CF_SQL_DATE"  VALUE="#listgetAt(i,9)#">,
    59 :                  <CFQUERYPARAM CFSQLTYPE="CF_SQL_DATE"  VALUE="#listgetAt(i,9)#">,
    60 :                  <CFQUERYPARAM CFSQLTYPE="cf_sql_varchar"  VALUE="#listgetAt(i,9)#">
    Also I can make my .csv file available for you if you need it. Also, the date is being inseted in this format: 3/3/1952

  • Content Tab: None of the fact tables are compatible with the query request

    Hi All,
    **One thing I am not clear yet of all my years with OBIEE is working with the content tab in BMM.**
    I have made a rpd the joins in physical layer as shown below:
    https://picasaweb.google.com/114804305606242416264/OBIEEError#5663056545119428530
    And the BMM layer as:
    https://picasaweb.google.com/114804305606242416264/OBIEEError#5663056519553812930
    Error I am getting when i run a request from the 3 columns from the selected 3 tables is:
    Dim - Comment Code Details
    Fact - Complaint
    Dim - Service Details
    Error Codes: OPR4ONWY:U9IM8TAC:OI2DL65P
    State: HY000. Code: 10058. [NQODBC] [SQL_STATE: HY000] [nQSError: 10058] A general error has occurred. [nQSError: 14020] None of the fact tables are compatible with the query request Sr Num:[DAggr(Fact - Complaint.Sr Num by [ Dim - Service Details.Sr Cat Type Cd, Dim - Comment Code Details.Cmtcode name] )]. (HY000).
    I get no error for consistency.. I read everywhere and I know i need to set the appropriate aggregation levels in the various dims and facts LTS properties to help OBIEE understanding our model, but how to do that.. how do i decide... how should I approach, what should be the aggregation level, what details.
    When i click More button i see different options: Copy, Copy From, Get Levels, Check Level, what do these mean.
    Aggregation Content, group by - Logical Level or Column which one should i choose and how should I decide.
    Can anyone explain the Content Tab in details and from scratch with some example and why we get these errors.... I know many people who are well versed with many other things related to RPD but this. A little efforts of explaining from you guys will really be appreciated.
    Thanks in advance,
    Dev

    Hi Deepak,
    Option 1:
    My tables in physical layer are joined as below:
    D1--> F1 <--D2--> F2 <--D3
    Same way i model it in BMM
    D1--> F1 <-- D2--> F2 <--D3
    Here D1 is non Conformed Dimension for F2 and D3 is non Conformed dim for F1. Later create Dimensional hierarchies, I tried setting up the content levels
    I go Sources>content tab of Fact F1 I set
    Dimensions----------- Logical level
    D1---------------------- D1 Detail
    D2---------------------- D2 Detail
    D3---------------------- D3 Total
    then, I go Sources>content tab of Fact F2 I set
    Dimensions----------- Logical level
    D1---------------------- D1 Total
    D2---------------------- D2 Detail
    D3---------------------- D3 Detail
    Then, I also go in all the dimensions and set their content levels to Details, but it still gives me errors not sure where I am going wrong in setting the content levels.
    I need to know whether the way I have modeled it in BMM is right,
    Option 2:
    I can combine the two facts in a single Logical Fact or the above design should also work.
    (F1&F2)<--D1, D2 , D3 joined separately using complex logical joins.
    what will be the content tab details?
    Thanks,
    Dev

Maybe you are looking for