Table variable

Hello,
I declared the following:
TYPE CustRecTable IS TABLE OF Customers_temp%ROWTYPE;
cust_recs CustRecTable;
and then I populate cust_recs from a cursor:
FETCH c_cust BULK COLLECT INTO cust_recs;
Everything works fine so far, I get approx. 500,000 records in cust_recs.
My question is:
How can I insert these records stored in cust_recs (or the cursor?) into a table that has exactly the same column structure?
Can I do this with a single PL/SQL statement or I need to loop? What would be the most efficient method?
I am using Oracle 11g R2.
Thank you,
M.R.
Edited by: user7047382 on Sep 8, 2010 1:49 PM

Skip the explicit cursors, loops and table types altogether. Do something like this:
INSERT INTO destination_table
( col1
, col2
, col3
SELECT col1
     , col2
     , col3
FROM   source_table
;Hope that helps. If you need further assistance please post the following information:
1. Oracle version (SELECT * FROM V$VERSION)
2. Sample data in the form of CREATE / INSERT statements.
3. Expected output
4. Explanation of expected output (A.K.A. "business logic")
5. Use \ tags for #2 and #3. See FAQ (Link on top right side) for details.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

Similar Messages

  • Open sys_refcursor for select from table variable?

    Hi,
    I've got a challenge for you! :-)
    I've got a procedure that has a lot of logic to determine what data should be loaded into a table variable. Because of various application constraints, i can not create a global temporary table. Instead, i'd like to create a table variable and populate it with stuff as i go through the procedure.
    The end result of the procedure is that i must be able to pass the results back as a sys_refcursor. This is a requirement that is beyond my control as well.
    Is there a way to make this sort of procedure work?
    Create Or Replace Procedure Xtst
    Mu_Cur In Out Sys_Refcursor
    Is
    Type Xdmlrectype Is Record (Col1 Varchar2(66));
    Type Xdmltype Is Table Of Xdmlrectype;
    Rtn Xdmltype;
    Begin
    Select Internal_Id Bulk Collect Into Rtn From Zc_State;
    open mu_cur for select col1 from table(rtn);
    end;
    11/42 PLS-00642: local collection types not allowed in SQL statements
    11/36 PL/SQL: ORA-22905: cannot access rows from a non-nested table item
    11/19 PL/SQL: SQL Statement ignored
    Show Errors;

    Not anything i'd want to personally implement.
    But for educational purposes only of course....
    create table this_will_be_gross
       column1 number,
       column2 varchar2(30)
    insert into this_will_be_gross values (1, 'begin the ugliness');
    insert into this_will_be_gross values (2, 'end the ugliness');
    variable x refcursor;
    ME_XE?
    declare
       Rtn sys.ODCIVARCHAR2LIST;
    BEGIN
       SELECT
          column1 || '-' || column2 Bulk Collect
       INTO
          Rtn
       FROM
          this_will_be_gross;
       OPEN :x FOR
       SELECT 
          regexp_substr (column_value, '[^-]+', 1, 1) as column1,
          regexp_substr (column_value, '[^-]+', 1, 2) as column2      
       FROM TABLE(CAST(rtn AS sys.ODCIVARCHAR2LIST));
    end;
    17  /
    PL/SQL procedure successfully completed.
    Elapsed: 00:00:00.09
    ME_XE?
    ME_XE?print :x
    COLUMN1                        COLUMN2
    1                              begin the ugliness
    2                              end the ugliness
    2 rows selected.
    Elapsed: 00:00:00.11In the above example i 'knew' that a hypen was a safe character to use to break up my data elements (as it would not be found anywhere in the data itself).
    I would strongly encourage you not to implement something like this. I realize it's tempting when you are working in strict environments where it can take a serious battle to get structures like temporary tables or SQL Types created, but that's really the proper approach to be taking.

  • Report cannot access pl/sql table variable defined in Package Spec.

    Hi,
    I've created a package spec called pkg_report with a PL/SQL table variable defined called body_text_table. When I tried to compile the following code under the Before Report trigger:
    :desc := pkg_report.body_text_table(1);
    Oracle gave me the following error:
    Implementation Restriction: 'PKG_REPORT.BODY_TEXT_TABLE': Cannot directly access remote package variable or cursor.
    Does anyone have any idea about this error? Thank you for your time at looking at it.
    Regards,
    John

    You cannot directly access the package variable in a database package. The work around is to create a set_variable and get_variable wrapper function in the package body. See Metalink note 105838.1 for more info.
    A simple example:
    create or replace package my_package as
      my_var     number;
      function   get_variable return number ;
      procedure  set_variable (p_value in number) ;
    end ;
    create or replace package body my_package as
      function get_variable return number is
      begin
        return my_var;
      end ;
      procedure set_variable(p_value in number) is
      begin
        my_var := p_value ;
      end ;
    end;

  • Using a dynamic table variable in a stored procedure

    SQL Server can do this where you declare a table variable and insert / modify / delete rows in that table without it ever being actually ON the database.
    Can Oracle do this?
    I know I can do things like pass in a unique user id, create the table in the procedure with the user ID appended, etc ...
    but this procedure is going to be accessed via two modes, a batch job as well as online. The batch job may run this procedure 500 times.
    What I'm trying to is figure out a way to return a recordset of errors that occured in the job, simple, 3 lines like so:
    LineNumber NUMBER,
    Severity VARCHAR(10),
    Error_Msg VARCHAR(200)
    is there any 3 dimensional way of storing these records when the errors occur, then returning them as a select statement at the end of the procedure?
    Thanks,

    Why not create a table
    CREATE TABLE error_log (
      job_id  NUMBER,
      line_number NUMBER,
      severity VARCHAR2(10),
      error_msg VARCHAR2(200)
    CREATE SEQUENCE seq_error_log_job_id
      START WITH 1
      INCREMENT BY 1
      CACHE 100;In your procedure, you would get a new job_id from the sequence, insert whatever records you want in the error log table using that job_id and then return a REF CURSOR where you select from the error_log table using the job_id.
    Justin
    Distributed Database Consulting, Inc.
    http://www.ddbcinc.com/askDDBC

  • 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

  • Oracle equivalent to SQL Server Table Variables ?

    Does Oracle have anything equivalent to SQL Server table variables, that can be used in the JOIN clause of a select statement ?
    What I want to do is execute a query to retrieve a two-column result, into some form of temporary storage (a collection ?), and then re-use that common data in many other queries inside a PL/SQL block. I could use temporary tables, but I'd like to avoid having to create new tables in the database, if possible. If I was doing this in SQL Server, I could use a table variable to do this, but is there anything similar in Oracle ? SQL Server example:
    use Northwind
    DECLARE @myVar TABLE(CustomerID nchar(5), CompanyName nvarchar(40))
    INSERT INTO @myVar(CustomerID, CompanyName)
    select CustomerID, CompanyName
    from Customers
    --Join the variable onto a table in the database
    SELECT *
    FROM @myVar mv join Customers
    on mv.CompanyName = Customers.CompanyName
    The closest I've found in Oracle is to use CREATE TYPE to create new types in the database, and use TABLE and CAST to convert the collection to a table, as shown below. I can't see anyway without creating new types in the database.
    CREATE TYPE IDMap_obj AS Object(OldID number(15), NewID number(15));
    CREATE TYPE IDMap_TAB IS TABLE OF IDMap_obj;
    DECLARE
    v_Count Number(10) := 0;
    --Initialize empty collection
    SourceIDMap IDMap_TAB := IDMap_TAB();
    BEGIN
    --Populate our SourceIDMap variable (dummy select statement for now).
    FOR cur_row IN (select ID As OldID, ID + 10000000 As NewID From SomeTable) LOOP
    SourceIDMap.extend;
    SourceIDMap(SourceIDMap.Last) := IDMap_obj(cur_row.OldId, cur_row.NewId);
    END LOOP;
    --Print out contents of collection
    FOR cur_row IN 1 .. SourceIDMap.Count LOOP
    DBMS_OUTPUT.put_line(SourceIDMap(cur_row).OldId || ' ' || SourceIDMap(cur_row).NewId);
    END LOOP;
    --OK, can we now use our collection in a JOIN statement ?
    SELECT COUNT(SM.NewID)
    INTO v_Count
    FROM SomeTable ST JOIN
    TABLE(CAST(SourceIDMap As IDMap_TAB)) SM
    ON ST.ID = SM.OldID;
    DBMS_OUTPUT.put_line(' ' );
    DBMS_OUTPUT.put_line('v_Count is ' || v_Count);
    END;

    Hi, got this from our plsql guys:
    The term "table function" is a bit confusing here. In Oracle-speak, it means a function that can be used in the from list of a select statement thus:
    select * from Table(My_Table_Function()),..
    where...
    The function's return type must be a collection that SQL understands. So for the interesting case -- mimicking a function with more than one column -- this would be a nested table of ADTs where both the ADT and the nested table are defined at schema level. PL/SQL -- by virtue of some clever footwork -- allows you to declare the type as a nested table of records where both these types are declared in a package spec. This alternative is generally preferred, especially because the nested table can be of Some_Table%rowtype (or Some_Cursor%rowtype if you prefer).
    As I understand it from our man on the ANSI committee, our use terminology follows the standard.
    The construct below seems to be a bit different (though there are similarities) because it appears from your code sample that it's usable only within procedural code. And the object from which you select is a variable rather than a function.
    So, after that preamble... the answer would be:
    No, we don't have any constructs to let you "declare" something that looks like a regular schema-level table as a PL/SQL variable -- and then use (static) SQL on it just as if it were a schema-level table.
    But yes, you can use PL/SQL's pipelined table function to achieve much of the same effect.
    Look at the attached Table_Function.sql.
    It shows that you can populate a collection of records using ordinary PL/SQL code. You can't use SQL for insert, update, or delete on such a collection. I see that SQL Server lets you do
    insert into Program_Variable_Table select... from Schema_Level_Table
    The PL/SQL equivalent would be
    select...
    bulk collect into Program_Variable_Collection
    from Schema_Level_Table
    The attached shows that once you have populated your collection, then you can then query it with regular SQL -- both from inside PL/SQL code and from naked SQL.
    and the code is here
    CONNECT System/p
    -- Drop and re-create "ordinary" user Usr
    EXECUTE d.u
    CONNECT Usr/p
    create table Schema_Things(ID number, Description Varchar2(80))
    create package Pkg is
    subtype Thing_t is Schema_Things%rowtype;
    type Things_t is table of Thing_t; -- index by pls_integer
    Things Things_t;
    -- PLS-00630: pipelined functions must have
    -- a supported collection return type
    -- for "type Things_t is table of Thing_t index by pls_integer".
    function Computed_Things return Things_t pipelined;
    procedure Insert_Schema_Things(No_Of_Rows in pls_integer);
    end Pkg;
    create package body Pkg is
    function Computed_Things return Things_t pipelined is
    Idx pls_integer;
    Thing Thing_t;
    begin
    Idx := Things.First();
    while Idx is not null loop
    pipe row (Things(Idx));
    Idx := Things.Next(Idx);
    end loop;
    end Computed_Things;
    procedure Insert_Schema_Things(No_Of_Rows in pls_integer) is
    begin
    Things := Things_t();
    Things.Extend(No_Of_Rows);
    for j in 1..No_Of_Rows loop
    Things(j).ID := j;
    Things(j).Description := To_Char(j, '00009');
    end loop;
    insert into Schema_Things
    select * from Table(Pkg.Computed_Things());
    end Insert_Schema_Things;
    end Pkg;
    -- Test 1.
    begin Pkg.Insert_Schema_Things(100); end;
    select * from Schema_Things
    -- Test 2.
    begin
    Pkg.Things := Pkg.Things_t();
    Pkg.Things.Extend(20);
    for j in 1..20 loop
    Pkg.Things(j).ID := j;
    Pkg.Things(j).Description := To_Char(j, '00009');
    end loop;
    for j in 1..5 loop
    Pkg.Things.Delete(5 +2*j);
    end loop;
    end;
    select * from Table(Pkg.Computed_Things())
    /

  • 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

  • Is it possible to create table variable by copying structure of existing table?

    Greetings community,
    It’s a newbie question.
    I’m still learning T-SQL, and I’m not very familiar with its syntax, so I’m not sure if I’m asking something stupid. I’m creating a “stored function”. I need to create temporary table variable to do some “thinking” in it and spit out a
    scalar result. Actually, I have to create about ten similar functions to process ten tables in similar way, so I was searching is it possible to speed it up.
    I was wondering is there any way, instead of declaring table variable with list of gazillion columns (and having the possibility to mistype something), to declare table variable so it would inherit structure of existing table.
    Thanks for any help.

    Temp table variable can not be created on the fly, but temp table can be created.
    If you want just the structure, you can use the below.
    SELECT Top 0
    INTO #temp
    FROM
    Sales.SalesOrderHeader

  • Internal table, variable,...when debug

    Hi all,
    Is there any place I can see all internal table, variable,.. of a running transaction?
    thanks.

    before excuting that transction in the command line enter '/h'
    after tht execute the transaction,.. in the debugg mode u can view all the internal tables, their values, etc..
    reward appropriate points.
    Regards,
    SIMI,

  • Simple command to refresh data of all declared internal tables & variables!

    Hi All,
    I have declared many internal tables & variables in my program in declaration include.
    Is there any Simple command which can refresh data of all declared internal tables & variables!
    Instead of clearing & refreshing each i.table & variable i want to use single command to refresh data.
    Is this possible!
    Thanks in advance.
    Thanks,
    Deep.

    CLEAR: lv_field1,
                 lv_field2,
                 lt_itab1[],
                 lt_itab2[].
    ONE simple command (CLEAR), can initialize fields, workareas, field-symbols,.... and internal tables.

  • Whats the difference betweeen passing the table variable and table valued parameter?

    Hi Everbody
      Can someone one tell me what's the difference between passing a table variable and table valued parameter to a stored procedure or function? Can both be used to pass a table to a stored procedure/function?
    Regards
    Regards

    They are essentially the same. What we call a table variable is a local
    variable. A table-valued parameter is an incoming parameter to the
    procedure. The only difference is that the parameter is readonly.
    When you call a stored procedure, you can pass a table variable as the
    actual parameter. Or a table-valued parameter that you pass on.
    CREATE PROCEDURE nisse_sp @tvp sometype READONLY AS
    DECLARE @local someothertabletype
    EXEC pelle_sp @tvp, @local
    Erland Sommarskog, SQL Server MVP, [email protected]

  • 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

  • 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

  • RecordSet message: Must Declare Table Variable

    Hi
    I am trying to read a table using a RecordSet
    Private oRecordSet As SAPbobsCOM.Recordset
    Dim oSqlString As String = "Select U_tno, U_cpro from @MX_N301"
    Try
            oRecordSet.DoQuery(oSqlString)
    Catch ex As Exception
    And ex receives the next message:[Microsoft][ODBC SQL Server Driver][SQL Server]Must declate table variable "@MX_N301"
    Can anybody tell me why I receive this message and what else do I have to do?
    Thanks a lot

    Hi Alberto,
    for tables with  @ you need brackets !
    "Select U_tno, U_cpro from [@MX_N301]"
    regards
    David

  • Table Variable properties/ uses?

    Dear Readers,
    I wanted to know how table variable works. Is it like a temp table where we cannot retrieve it after the connection is dropped or is it retrievable?
    DECLARE @MyTable TABLE
       id        INT NOT NULL,
       fname    VARCHAR(20)
    I read somewhere that we can use it in a  stored procedure, that means it must be saved somewhere in order to be retrieved?
    Thanks for clarifying the concept/issue.
    Regards
    SQL 75

    Nope its like a local variable but of table type
    ie its scope is only within the batch where you created it
    see this example
    declare @t table
    v varchar(100)
    insert @t
    values('uyty1231314'),('qweq2142423uyiy')
    --here you will get result
    select *
    from @t
    --end of batch table variable becomes out of scope and destroyed
    GO
    --this will throw error as table variable doesnt exist any more
    select *
    from @t
    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

  • 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

Maybe you are looking for

  • Creating text boxes is causing VERY slow performance

    i've read the threads about how slow indesign cc has been from last year.  i would assume this issue had been fixed by now, so i just switched our whole company over from cs5 to cc.  we are a prinitng company that makes calendars with many text boxes

  • How can I send HTML emails that display in Mail?

    Hi, I have an email newsletter that I recently have begun experimenting with in HTML. The problem is, when I try to use HTML, the message displays properly in things like Yahoo! webmail, but in Mail for OSX, it displays like a regular text message, i

  • How to test if a server is running before connecting?

    If I have a Socket trying to open a connection to a certain IP, is there a way to test this first before I use a new Socket and it throws an Exception? Like I would like to try to connnect 5 times to a server before giving up.

  • FileSender Adapter - Recordset Structure Problem

    Hi, I would like to know if it is possible to create a recordset structure in the FileSender Adapter for a flatfile where certain Record Types might reoccur. The source structure is as follows: 3222:003:051201:093056:7596:001:F:100:0011:             

  • Hi,   search help     --   restricted value

    hi there is already a search help for a field in one of the transaction codes in fico. i think this search help is attached in code by writing match code syntax. but my prob is that this search help for the particular field shows 10 char and out of t