Drop and recreate table in stored procedure

Hi all
When creating tables using Transact-SQL scripts, I have always preferred to drop the table if it exists and then create it explicitly using CREATE TABLE.  For two reasons:
1) It does not matter if it is the first time the SP is run ie. if I create the table manually in the first instance and just use TRUNCATE TABLE it could fail if the table is deleted
2) I have control over the data types of the table fields
Just recently though I discovered the error that can occur when dropping and creating a table in the same batch (see link below)
Microsoft Website
This causes me a problem when dropping and creating tables in stored procedures, as I understand that a stored procedure is in itself a single batch?
Can I avoid this error in a stored procedure whilst continuing to drop and create tables?  Or should I be taking a different approach?
Coding best practice advice would be greatly appreciated.
Thank you

Thanks Ronen
Please see my second post immediately before your reply.
Given that I need to store the data output in a physical table for use in QlikView, would you suggest truncating the table each time the SP runs?  And then having a script that handles both dropping and creating the physical table, and also creating
the SP?
>> QlikView
QlikView is an Israeli company, right?
In any case I am not familiar with QlikView's application, therefore I can only give you general information, based on assumptions regarding the application, and facts regarding the SQL Server.
>> for use in QlikView
I assume that external application use specific database structure (table
structure) and it is change only in rare situations (for example CMS interface might change the tables if and when a module s update/install). In this case there is no need to drop the table and recreate it and TRUNCATE is the solution.
>> would you suggest truncating the table each time the SP runs
I am sorry but i cant recommend on TRUNCATE a table each time you execute SP, without know the exact reason for this logic. It sound to me, at this point of time (with the information that we have), that this
is very bad logic (application architecture). As I wrote above, basing your application on TRUNCATING the table each time mean that you have problems with multi users. Thins about 2 people that try to execute the same SP at almost the same time. Think about
locking in the SQL Server and bad data (one truncate while the other already inserted the new data and get no rows, if there is no locking).
But TRUNCATE is much better in this case probably then DROP and DELETE, since it is faster, and locking will be shorter (hopefully the application use the correct locking). There are other reasons why TRUNCATE is better, and other people already mentioned
most of them, but time in this scenario might be critical.
>> having a script that handles both dropping and creating the physical table, and also creating the SP?
I do not undestand what is this second step. we said that you truncate the table, so why do you need to
dropping and creating the physical table and who
creating the SP?
Are you meaning that the application create the tables and SP?
There are lot of application that during installation create the database structure. is this what you mean?
  Ronen Ariely
 [Personal Site]    [Blog]    [Facebook]

Similar Messages

  • Synonyms cant be recompiled when the tables are dropped and recreated?

    hi
    i have a synonym pointing to a table .
    1)when i drop and recreate a table.............
    isnt it enough to recompile the synonym? do i need to drop the synonym as well and recreate again?
    2) when i add new columns to a table will the synonym also show up the new column?
    thanks in advance
    raj

    Recompiled is probably not quite the correct word. Re-validated is more like it.
    Notice that the synonym goes invalid when the table is dropped, but does NOT become valid when the table is recreated.
    That happens the first time it's used (similar to invalid stored procedures).
    SQL> drop table t;
    Table dropped.
    SQL> select object_name, status
      2  from user_objects
      3  where object_name = 'T_SYN';
    OBJECT_NAME                    STATUS
    T_SYN                          INVALID
    SQL> create table t(c number);
    Table created.
    SQL> select object_name, status
      2  from user_objects
      3  where object_name = 'T_SYN';
    OBJECT_NAME                    STATUS
    T_SYN                          INVALID
    SQL> select * from t_syn;
    no rows selected
    SQL> select object_name, status
      2  from user_objects
      3  where object_name = 'T_SYN';
    OBJECT_NAME                    STATUS
    T_SYN                          VALID

  • What is the best way to drop and recreate a Primary Key in the Replication Table?

    I have a requirement to drop and recreate a primary key in a table which is part of Transaction replication. What is the best way to fo it other than remove it from replication and add again?
    Thanks
    Swapna

    Hi Swapna,
    Unfortunately you cannot drop columns used in a primary key from articles in transactional replication.  This is covered in
    Make Schema Changes on Publication Databases:
    You cannot drop columns used in a primary key from articles in transactional publications, because they are used by replication.
    You will need to drop the article from the publication, drop and recreate the primary key, and add the article back into the publication.
    To avoid having to send a snapshot down to the subscriber(s), you could specify the option 'replication support only' for the subscription.  This would require the primary key be modified at the subscriber as well prior to adding the article back in
    and should be done during a maintenance window when no activity is occurring on the published tables.
    I suggest testing this out in your test environment first, prior to deploying to production.
    Brandon Williams (blog |
    linkedin)

  • Using temporary tables in stored procedures

    Suppose that I have created a temporary table in a stored procedure using an "EXECUTE IMMEDIATE" statement. When I compile the procedure, that table is not created yet, so the compiler says that the table does not exist.
    What is the way of using temporary tables in stored procedures?

    It's a good practice to avoid using DDL statements being executed from stored procedures. "Truncate Table" via dynamic SQL from stored procedure is a different story and is useful in DSS environments.
    But if you insist on "creating" tables using Dynamic SQL from Stored Procedures then you must also embed your DML statements in Dynamic SQL to avoid compilation errors.
    Example:
    Create or Replace Procedure Proc_TestDynamicSQL is
    Begin
    Execute Immediate 'Create table myTable as select * from user_tables' ;
    Execute Immediate 'Update myTable set table_name = ''Test'' ' ; --two single quotes before and after the string "Test"
    End;
    In this case, Oracle wouldn't care about the table references during compilation.

  • Sys Tables In Stored Procedure

    How can I use Sys Table in Stored Procedure.
    I want to use DBA_TAB_COLOUMNS, in stored procedure.
    When I used this table in stored procedure I got an error
    ORA - 00942 Table or View Does not exists.
    Thanks,
    Ahamed

    From http://download.oracle.com/docs/cd/B19306_01/appdev.102/b14251/adfns_packages.htm#i1006224
    >
    Note:
    To create without errors (to compile the procedure or package successfully) requires the following additional privileges:
    The owner of the procedure or package must be explicitly granted the necessary object privileges for all objects referenced within the body of the code.
    The owner cannot obtain required privileges through roles.
    >
    You need to run
    grant select on dba_tab_columns to <owner of procedure>;

  • EMDATABASEControl emca drop and recreate in RAC

    Any body know how to drop and recreate EMDATABASEControl (emca) drop and recreate for RAC DB?

    use emca -help you can get the parameters used to de-configure and re-configure the emca for RAC
    $emca -help
    -deleteInst (db | asm) [-silent] [parameters]: de-configure EM for a specified RAC instance
    -reconfig dbcontrol -cluster [-silent] [parameters]: reconfigures RAC Database Control deployment

  • RE: Drop and recreate user

    Hi,
    If we drop and recreate the oracle user in production database, what advantages we will get?
    Any one help me...
    DB Version:10.2.04
    OS: HP-UX
    Thanks,
    Srini ...

    935930 wrote:
    Hi,
    If we drop and recreate the oracle user in production database, what advantages we will get?
    Any one help me...
    DB Version:10.2.04
    OS: HP-UX
    Thanks,
    Srini ...The "advantage" (or "disadvantage") would depend on what you are trying to accomplish, correct?

  • Way to programmatically drop-and-create-tables?

    Hi all,
    I have a persistence unit which exists to provide lookup information to my application. It is populated by data that is available at runtime. It takes a long time to parse this data, and therefore my intention is to only parse it once at the deployment target. To do this, I have created a main method that does all the parsing, and I do not set the toplink.ddl-generation property in persistence.xml. This causes the application to fail if the database is not created.
    However, this means that during the population stage, I must drop and create any existing tables. I had thought it would be possible to do this by obtaining an EntityManagerFactory which has a property map sent to it, containing the property toplink.ddl-generation set to drop-and-create-tables. But this does not work... the tables are not dropped (if they exist) and are not created (if the database is empty).
    Is it possible to do the drop-and-create-tables programmatically using the JPA?
    I may have another EntityManagerFactory open at the same time, which has been opened with the default options... would this be conflicting?

    I don't think there is any easy way to generate the default tables once your have created the EntityManagerFactory. You could use the EclipseLink/TopLink schemaframework or TableCreator to create tables using a EclipseLink/TopLink DatabaseSession.
    There is a DefaultTableGenerator in org.eclipse.persistence.tools.schemaframework, which may give you what you are looking for.
    -- James : http://www.eclipselink.org

  • How to create stored procedure to drop and create table

    Version: Oracle 10g
    I am trying to create a stored procedure that will drop and create a table based on a select statement. I can create the table but I can't drop it.
    CREATE OR REPLACE procedure EC_LOAD is
    begin
    INSERT INTO Sales_table
    (FSCL_WK,
    DIV,
    ACCT_TYPE)
    Select
    FSCL_WK,
    DIV,
    ACCT_TYPE
    from
    sales_revenue;
    end ecload;
    I need to drop Sales_table before inserting the values. How do i do this?

    Or with a drop:
    SQL> desc emp2
    ERROR:
    ORA-04043: object emp2 does not exist
    SQL>
    SQL> declare
      2    cnt      int := 0;
      3  begin
      4    select max (1)
      5      into cnt
      6      from user_tables
      7     where table_name = 'EMP2';
      8
      9    if cnt = 1
    10    then
    11      execute immediate 'drop table emp2';
    12    end if;
    13
    14    execute immediate 'create table emp2 as select * from emp';
    15  end;
    16  /
    PL/SQL procedure successfully completed.
    SQL>
    SQL> desc emp2
    Name                                      Null?    Type
    EMPNO                                              NUMBER(4)
    ENAME                                              VARCHAR2(10)
    JOB                                                VARCHAR2(9)
    MGR                                                NUMBER(4)
    HIREDATE                                           DATE
    SAL                                                NUMBER(7,2)
    COMM                                               NUMBER(7,2)
    DEPTNO                                             NUMBER(2)
    SQL>

  • List tables and column names a stored procedure is querying

    Hello,
    Is there a way to list tables and column names that a stored procedure is querying, i.e, selecting from, using T-SQL?  If yes, is there a way to also show data types for the columns that a stored procedure is querying, i.e, selecting from?
    Thank you,  
    Lenfinkel

    One way to view the dependencies of an object is to use SSMS; navigate to the object, right click and select "view dependencies".  However this does not tell you what columns are being referenced by the Stored Procedure.
    One way to view what is being referenced by a stored procedure is to run something like
    select
    text
    from syscomments
    where
    id in
    (select id
    from sysobjects
    where
    name
    =[Your Object Name]
    And xtype
    in
    ('p','P')
    Please click "Mark As Answer" if my post helped. Tony C.

  • When inserting 2 column details in a single table using Stored Procedure.Only 2 Column details getting inserted.1column details are not getting into the table.Please see the below script and help me to change.

    Line 390 Under the (Insert into SALES_TRADEIN Table)
    I need to insert (TradeIn_1_VIN) Values If there is no values in (TradeIn_1_VIN) then i have to insert (TradeIn_2_VIN) values to the (SALES_TRADEIN) Table.
    After i run then below script only (TradeIn_2_VIN) values are get inserted in the table. (TradeIn_1_VIN) are not getting loaded in to the table.
    I think there is the problem from Line No (404 to 414) Please help me change those particular lines to insert (TradeIn_1_VIN) Values also.If there is no details then (TradeIn_2_VIN) need to be inserted.
    -- =============================================
    -- Stored Procedure for Flatfile_Sales
    -- =============================================
    USE [IconicMarketing]
    ---==========Sales_Cursor
    --USE [IconicMarketing]
    --GO
    DECLARE
    @FileType
    varchar(50),
    @ACDealerID
    varchar(50),
    @ClientDealerID
    varchar(50),
    @DMSType
    varchar(50),
    @DealNumber
    varchar(50),
    @CustomerNumber
    varchar(50),
    @CustomerName
    varchar(50),
    @CustomerFirstName
    varchar(50),
    @CustomerLastName
    varchar(50),
    @CustomerAddress
    varchar(50),
    @CustomerCity
    varchar(50),
    @CustomerState
    varchar(50),
    @CustomerZip
    varchar(50),
    @CustomerCounty
    varchar(50),
    @CustomerHomePhone
    varchar(50),
    @CustomerWorkPhone
    varchar(50),
    @CustomerCellPhone
    varchar(50),
    @CustomerPagerPhone
    varchar(50),
    @CustomerEmail
    varchar(50),
    @CustomerBirthDate
    varchar(50),
    @MailBlock
    varchar(50),
    @CoBuyerName
    varchar(50),
    @CoBuyerFirstName
    varchar(50),
    @CoBuyerLastName
    varchar(50),
    @CoBuyerAddress
    varchar(50),
    @CoBuyerCity
    varchar(50),
    @CoBuyerState
    varchar(50),
    @CoBuyerZip
    varchar(50),
    @CoBuyerCounty
    varchar(50),
    @CoBuyerHomePhone
    varchar(50),
    @CoBuyerWorkPhone
    varchar(50),
    @CoBuyerBirthDate
    varchar(50),
    @Salesman_1_Number
    varchar(50),
    @Salesman_1_Name
    varchar(50),
    @Salesman_2_Number
    varchar(50),
    @Salesman_2_Name
    varchar(50),
    @ClosingManagerName
    varchar(50),
    @ClosingManagerNumber
    varchar(50),
    @F_AND_I_ManagerNumber
    varchar(50),
    @F_AND_I_ManagerName
    varchar(50),
    @SalesManagerNumber
    varchar(50),
    @SalesManagerName
    varchar(50),
    @EntryDate
    varchar(50),
    @DealBookDate
    varchar(50),
    @VehicleYear
    varchar(50),
    @VehicleMake
    varchar(50),
    @VehicleModel
    varchar(50),
    @VehicleStockNumber
    varchar(50),
    @VehicleVIN
    varchar(50),
    @VehicleExteriorColor
    varchar(50),
    @VehicleInteriorColor
    varchar(50),
    @VehicleMileage
    varchar(50),
    @VehicleType
    varchar(50),
    @InServiceDate
    varchar(50),
    @HoldBackAmount
    varchar(50),
    @DealType
    varchar(50),
    @SaleType
    varchar(50),
    @BankCode
    varchar(50),
    @BankName
    varchar(50),
    @SalesmanCommission
    varchar(50),
    @GrossProfitSale
    varchar(50),
    @FinanceReserve
    varchar(50),
    @CreditLifePremium
    varchar(50),
    @CreditLifeCommision
    varchar(50),
    @TotalInsuranceReserve
    varchar(50),
    @BalloonAmount
    varchar(50),
    @CashPrice
    varchar(50),
    @AmountFinanced
    varchar(50),
    @TotalOfPayments
    varchar(50),
    @MSRP varchar(50),
    @DownPayment
    varchar(50),
    @SecurityDesposit
    varchar(50),
    @Rebate
    varchar(50),
    @Term varchar(50),
    @RetailPayment
    varchar(50),
    @PaymentType
    varchar(50),
    @RetailFirstPayDate
    varchar(50),
    @LeaseFirstPayDate
    varchar(50),
    @DayToFirstPayment
    varchar(50),
    @LeaseAnnualMiles
    varchar(50),
    @MileageRate
    varchar(50),
    @APRRate
    varchar(50),
    @ResidualAmount
    varchar(50),
    @LicenseFee
    varchar(50),
    @RegistrationFee
    varchar(50),
    @TotalTax
    varchar(50),
    @ExtendedWarrantyName
    varchar(50),
    @ExtendedWarrantyTerm
    varchar(50),
    @ExtendedWarrantyLimitMiles
    varchar(50),
    @ExtendedWarrantyDollar
    varchar(50),
    @ExtendedWarrantyProfit
    varchar(50),
    @FrontGross
    varchar(50),
    @BackGross
    varchar(50),
    @TradeIn_1_VIN
    varchar(50),
    @TradeIn_2_VIN
    varchar(50),
    @TradeIn_1_Make
    varchar(50),
    @TradeIn_2_Make
    varchar(50),
    @TradeIn_1_Model
    varchar(50),
    @TradeIn_2_Model
    varchar(50),
    @TradeIn_1_ExteriorColor
    varchar(50),
    @TradeIn_2_ExteriorColor
    varchar(50),
    @TradeIn_1_Year
    varchar(50),
    @TradeIn_2_Year
    varchar(50),
    @TradeIn_1_Mileage
    varchar(50),
    @TradeIn_2_Mileage
    varchar(50),
    @TradeIn_1_Gross
    varchar(50),
    @TradeIn_2_Gross
    varchar(50),
    @TradeIn_1_Payoff
    varchar(50),
    @TradeIn_2_Payoff
    varchar(50),
    @TradeIn_1_ACV
    varchar(50),
    @TradeIn_2_ACV
    varchar(50),
    @Fee_1_Name
    varchar(50),
    @Fee_1_Fee
    varchar(50),
    @Fee_1_Commission
    varchar(50),
    @Fee_2_Name
    varchar(50),
    @Fee_2_Fee
    varchar(50),
    @Fee_2_Commission
    varchar(50),
    @Fee_3_Name
    varchar(50),
    @Fee_3_Fee
    varchar(50),
    @Fee_3_Commission
    varchar(50),
    @Fee_4_Name
    varchar(50),
    @Fee_4_Fee
    varchar(50),
    @Fee_4_Commission
    varchar(50),
    @Fee_5_Name
    varchar(50),
    @Fee_5_Fee
    varchar(50),
    @Fee_5_Commission
    varchar(50),
    @Fee_6_Name
    varchar(50),
    @Fee_6_Fee
    varchar(50),
    @Fee_6_Commission
    varchar(50),
    @Fee_7_Name
    varchar(50),
    @Fee_7_Fee
    varchar(50),
    @Fee_7_Commission
    varchar(50),
    @Fee_8_Name
    varchar(50),
    @Fee_8_Fee
    varchar(50),
    @Fee_8_Commission
    varchar(50),
    @Fee_9_Name
    varchar(50),
    @Fee_9_Fee
    varchar(50),
    @Fee_9_Commission
    varchar(50),
    @Fee_10_Name
    varchar(50),
    @Fee_10_Fee
    varchar(50),
    @Fee_10_Commission
    varchar(50),
    @ContractDate
    varchar(50),
    @InsuranceName
    varchar(50),
    @InsuranceAgentName
    varchar(50),
    @InsuranceAddress
    varchar(50),
    @InsuranceCity
    varchar(50),
    @InsuranceState
    varchar(50),
    @InsuranceZip
    varchar(50),
    @InsurancePhone
    varchar(50),
    @InsurancePolicyNumber
    varchar(50),
    @InsuranceEffectiveDate
    varchar(50),
    @InsuranceExpirationDate
    varchar(50),
    @InsuranceCompensationDeduction
    varchar(50),
    @TradeIn_1_InteriorColor
    varchar(50),
    @TradeIn_2_InteriorColor
    varchar(50),
    @PhoneBlock
    varchar(50),
    @LicensePlateNumber
    varchar(50),
    @Cost varchar(50),
    @InvoiceAmount
    varchar(50),
    @FinanceCharge
    varchar(50),
    @TotalPickupPayment
    varchar(50),
    @TotalAccessories
    varchar(50),
    @TotalDriveOffAmount
    varchar(50),
    @EmailBlock
    varchar(50),
    @ModelDescriptionOfCarSold
    varchar(50),
    @VehicleClassification
    varchar(50),
    @ModelNumberOfCarSold
    varchar(50),
    @GAPPremium
    varchar(50),
    @LastInstallmentDate
    varchar(50),
    @CashDeposit
    varchar(50),
    @AHPremium
    varchar(50),
    @LeaseRate
    varchar(50),
    @DealerSelect
    varchar(50),
    @LeasePayment
    varchar(50),
    @LeaseNetCapCost
    varchar(50),
    @LeaseTotalCapReduction
    varchar(50),
    @DealStatus
    varchar(50),
    @CustomerSuffix
    varchar(50),
    @CustomerSalutation
    varchar(50),
    @CustomerAddress2
    varchar(50),
    @CustomerMiddleName
    varchar(50),
    @GlobalOptOut
    varchar(50),
    @LeaseTerm
    varchar(50),
    @ExtendedWarrantyFlag
    varchar(50),
    @Salesman_3_Number
    varchar(50),
    @Salesman_3_Name
    varchar(50),
    @Salesman_4_Number
    varchar(50),
    @Salesman_4_Name
    varchar(50),
    @Salesman_5_Number
    varchar(50),
    @Salesman_5_Name
    varchar(50),
    @Salesman_6_Number
    varchar(50),
    @Salesman_6_Name
    varchar(50),
    @APRRate2
    varchar(50),
    @APRRate3
    varchar(50),
    @APRRate4
    varchar(50),
    @Term2
    varchar(50),
    @SecurityDeposit2
    varchar(50),
    @DownPayment2
    varchar(50),
    @TotalOfPayments2
    varchar(50),
    @BasePayment
    varchar(50),
    @JournalSaleAmount
    varchar(50),
    @IndividualBusinessFlag
    varchar(50),
    @InventoryDate
    varchar(50),
    @StatusDate
    varchar(50),
    @ListPrice
    varchar(50),
    @NetTradeAmount
    varchar(50),
    @TrimLevel
    varchar(50),
    @SubTrimLevel
    varchar(50),
    @BodyDescription
    varchar(50),
    @BodyDoorCount
    varchar(50),
    @TransmissionDesc
    varchar(50),
    @EngineDesc
    varchar(50),
    @TypeCode
    varchar(50),
    @SLCT2
    varchar(50),
    @DealDateOffset
    varchar(50),
    @AccountingDate
    varchar(50),
    @CoBuyerCustNum
    varchar(50),
    @CoBuyerCell
    varchar(50),
    @CoBuyerEmail
    varchar(50),
    @CoBuyerSalutation
    varchar(50),
    @CoBuyerPhoneBlock
    varchar(50),
    @CoBuyerMailBlock
    varchar(50),
    @CoBuyerEmailBlock
    varchar(50),
    @RealBookDate
    varchar(50),
    @CoBuyerMiddleName
    varchar(50),
    @CoBuyerCountry
    varchar(50),
    @CoBuyerAddress2
    varchar(50),
    @CoBuyerOptOut
    varchar(50),
    @CoBuyerOccupation
    varchar(50),
    @CoBuyerEmployer
    varchar(50),
    @Country
    varchar(50),
    @Occupation
    varchar(50),
    @Employer
    varchar(50),
    @Salesman2Commission
    varchar(50),
    @BankAddress
    varchar(50),
    @BankCity
    varchar(50),
    @BankState
    varchar(50),
    @BankZip
    varchar(50),
    @LeaseEstimatedMiles
    varchar(50),
    @AFTReserve
    varchar(50),
    @CreditLifePrem
    varchar(50),
    @CreditLifeRes
    varchar(50),
    @AHRes
    varchar(50),
    @Language
    varchar(50),
    @BuyRate
    varchar(50),
    @DMVAmount
    varchar(50),
    @Weight
    varchar(50),
    @StateDMVTotFee
    varchar(50),
    @ROSNumber
    varchar(50),
    @Incentives
    varchar(50),
    @CASS_STD_LINE1
    varchar(50),
    @CASS_STD_LINE2
    varchar(50),
    @CASS_STD_CITY
    varchar(50),
    @CASS_STD_STATE
    varchar(50),
    @CASS_STD_ZIP
    varchar(50),
    @CASS_STD_ZIP4
    varchar(50),
    @CASS_STD_DPBC
    varchar(50),
    @CASS_STD_CHKDGT
    varchar(50),
    @CASS_STD_CART
    varchar(50),
    @CASS_STD_LOT
    varchar(50),
    @CASS_STD_LOTORD
    varchar(50),
    @CASS_STD_URB
    varchar(50),
    @CASS_STD_FIPS
    varchar(50),
    @CASS_STD_EWS
    varchar(50),
    @CASS_STD_LACS
    varchar(50),
    @CASS_STD_ZIPMOV
    varchar(50),
    @CASS_STD_Z4LOM
    varchar(50),
    @CASS_STD_NDIAPT
    varchar(50),
    @CASS_STD_NDIRR
    varchar(50),
    @CASS_STD_LACSRT
    varchar(50),
    @CASS_STD_ERROR_CD
    varchar(50),
    @NCOA_AC_ID
    varchar(50),
    @NCOA_COA_ADDSRC
    varchar(50),
    @NCOA_COA_MATCH
    varchar(50),
    @NCOA_COA_MOVTYP
    varchar(50),
    @NCOA_COA_DATE
    varchar(50),
    @NCOA_COA_DELCD
    varchar(50),
    @NCOA_COA_RTYPE
    varchar(50),
    @NCOA_COA_RTNCD
    varchar(50),
    @NCOA_COA_LINE1
    varchar(50),
    @NCOA_COA_LINE2
    varchar(50),
    @NCOA_COA_CITY
    varchar(50),
    @NCOA_COA_STATE
    varchar(50),
    @NCOA_COA_ZIP
    varchar(50),
    @NCOA_COA_ZIP4
    varchar(50),
    @NCOA_COA_DPBC
    varchar(50),
    @NCOA_COA_CHKDGT
    varchar(50),
    @NCOA_COA_CART
    varchar(50),
    @NCOA_COA_LOT
    varchar(50),
    @NCOA_COA_LOTORD
    varchar(50),
    @NCOA_COA_URB
    varchar(50),
    @NCOA_COA_Z4LOM
    varchar(50),
    @NCOA_COA_ACTION
    varchar(50),
    @NCOA_COA_QNAME
    varchar(50),
    @NCOA_DPV_AA
    varchar(50),
    @NCOA_DPV_A1
    varchar(50),
    @NCOA_DPV_BB
    varchar(50),
    @NCOA_DPV_CC
    varchar(50),
    @NCOA_DPV_M1
    varchar(50),
    @NCOA_DPV_M3
    varchar(50),
    @NCOA_DPV_N1
    varchar(50),
    @NCOA_DPV_P1
    varchar(50),
    @NCOA_DPV_P3
    varchar(50),
    @NCOA_DPV_RR
    varchar(50),
    @NCOA_DPV_R1
    varchar(50),
    @NCOA_DPV_STATUS
    varchar(50),
    @NCOA_DPV_F1
    varchar(50),
    @NCOA_DPV_G1
    varchar(50),
    @NCOA_DPV_U1
    varchar(50),
    @myerror
    varchar(500),
    @SalesID
    int,
    @errornumber int,
                @errorseverity varchar(500),
                @errorstate int,
                @errorprocedure varchar(500),
                @errorline varchar(50),
                @errormessage varchar(1000);
    DECLARE Sales_Cursor CURSOR FOR 
    SELECT * from FLATFILE_SALES;
    OPEN Sales_Cursor;
     :r C:\Clients\BlackBook\BlackBookMarketing\Bharath\LOG_SALES_INSERT.sql
    WHILE @@FETCH_STATUS = 0
    BEGIN
    PRINT @VehicleVIN    ;
    --===============================================================================
    -- ****************** insert into Sales Table ***********
    BEGIN TRY
        INSERT INTO Sales 
    IconicDealerID,
    DealNumber,
    CustomerNumber,
    DMSType,
    ContractDate
    VALUES (@ClientDealerID,@DealNumber,@CustomerNumber,@DMSType,@ContractDate);
    END TRY
    BEGIN CATCH
         SELECT
            @errornumber = ERROR_NUMBER()
            ,@errorseverity = ERROR_SEVERITY() 
            ,@errorstate = ERROR_STATE() 
            ,@errorprocedure = ERROR_PROCEDURE() 
            ,@errorline = ERROR_LINE()
            ,@errormessage = ERROR_MESSAGE();
           :r C:\Clients\BlackBook\BlackBookMarketing\Bharath\LOG_SALES_INSERT.sql
    @errornumber ,
                @errorseverity ,
                @errorstate,
                @errorprocedure,
                @errorline,
                @errormessage);
    END CATCH
    PRINT @errornumber;
    PRINT @errorseverity;
    PRINT @errorprocedure;
    PRINT @errorline;
    PRINT @errormessage;
    PRINT @errorstate;
    set @myerror = @@ERROR;
        -- This PRINT statement prints 'Error = 0' because
        -- @@ERROR is reset in the IF statement above.
        PRINT N'Error = ' + @myerror;
    set @SalesID = scope_identity();
    PRINT @SalesID;
    --================================================================================
    --Insert into SALES_TRADEIN Table
    BEGIN TRY
    INSERT INTO SALES_TRADEIN
    SalesID,
    TradeIn_VIN,
    TradeIn_Make,
    TradeIn_Model,
    TradeIn_ExteriorColor,
    TradeIn_Year,
    TradeIn_Mileage,
    TradeIn_Gross,
    TradeIn_Payoff,
    TradeIn_ACV,
    TradeIn_InteriorColor
    VALUES
    @SalesID,
    case when  @TradeIn_1_VIN is not null then @TradeIn_2_VIN end,
    case when  @TradeIn_1_Make is not null  then @TradeIn_2_Make end,
    case when  @TradeIn_1_Model is not null  then @TradeIn_2_Model end,
    case when  @TradeIn_1_ExteriorColor is not null  then @TradeIn_2_ExteriorColor end,
    case when @TradeIn_1_Year is not null  then @TradeIn_2_Year end,
    case when  @TradeIn_1_Mileage is not null  then @TradeIn_2_Mileage end,
    case when @TradeIn_1_Gross is not null  then @TradeIn_2_Gross end,
    case when @TradeIn_1_Payoff is not null  then @TradeIn_2_Payoff end,
    case when @TradeIn_1_ACV is not null  then @TradeIn_2_ACV end,
    case when  @TradeIn_1_InteriorColor is not null  then @TradeIn_2_InteriorColor end
    END TRY
    BEGIN CATCH
    SELECT
            @errornumber = ERROR_NUMBER()
            ,@errorseverity = ERROR_SEVERITY() 
            ,@errorstate = ERROR_STATE() 
            ,@errorprocedure = ERROR_PROCEDURE() 
            ,@errorline = ERROR_LINE()
            ,@errormessage = ERROR_MESSAGE();
          :r C:\Clients\BlackBook\BlackBookMarketing\Bharath\LOG_SALES_INSERT.sql
    END CATCH

    This is what I've understood from your question. You want to replace @TradeIn_2_VIN value if @TradeIn_1_VIN
    is NULL, else the value of @TradeIn_1_VIN.
    If this is the requirement then, your CASE statement is missing ELSE part. You can re-write this as below
    case when  @TradeIn_1_VIN is null then @TradeIn_2_VIN
    ELSE @TradeIn_1_VIN end,
    or simply you can replace the CASE statement with the below
    COALESCE function,
    COALESCE(@TradeIn_1_VIN, @TradeIn_2_VIN),
    Krishnakumar S

  • DDL statements and dynamic  sql  in stored procedure

    I created a stored procedure to create and drop tables, using dynamic sql.
    When I try to do the inserts using dynamic sql, i.e
    v_string := 'INSERT statement';
    EXECUTE IMMEDIATE v_string;
    I get the following error message:
    ERROR at line 1:
    ORA-00942: table or view does not exist
    ORA-06512: at line 63
    Line 63 happens to be the line that the EXECUTE IMMEDIATE v_string; statement is in.
    I am able to describe the table that the inserts are being made into, so I know that the table exists.
    Any idea why I'm getting this error message would be appreciated.

    Yes I do and I have been able to create other tables using dynamic sql.
    The table that I am having problems with SELECTs data from another table to get its column values; within the SELECT statement, the CAST function is used:
    ie. CAST(CASE SUBSTR(CAST(E_MOD AS VARCHAR(7)),2,3)
    WHEN 'AAA' THEN 'A55'
    ELSE ............
    I get the following error message:
    ERROR at line 18: (this line starts the CAST statement)
    ORA-06550: line 18, column 13:
    PLS-00103: Encountered the symbol "AAA" when expecting one of the following:
    . ( * @ % & = - + ; < / > at in is mod not rem return
    returning <an exponent (**)> <> or != or ~= >= <= <> and or
    like between into using || bulk
    When I remove the quotes or add another single quote, the same error cascades to 'A55'.
    After doing the same for the next error, I get the error message below:
    ERROR at line 1: (this line has the EXECUTE IMMEDIATE statement)
    ORA-00936: missing expression
    ORA-06512: at line 6
    Any idea what the problem could be?
    Also is there another way to have DDL statements as stored procedures other than using dynamic sql or the DBMS_SQL package?

  • Temporary Tables in Stored Procedure

    Hi,
    I am writing a stored procedure that will get data from different sources and generates a spreadsheet finally. Initial select gets the basic data and following selects merges data.
    For this I have created a table in the database, I am populating data into that table using same procedure and finally selecting data from that table to generate spreadsheet.
    Now I am planning to use TEMPORARY table instead of creating table in database. Can anyone tell me where I can view samples for temp tables?
    Which one is the better option in performance wise?
    or
    can I handle the whole scenario with cursor? any examples?

    Hi,
    Why can't you use a regular table?
    Look up [Global Temporary|http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/statements_7002.htm#sthref7247] in the diocumentation, including the SQL*Language manual, for an alternative.
    "Temporary" applies only to the data. A Global Temporary Table is created once, and stays until you DROP it, the same as any other table.
    The data in the table is temporary. If you create the table saying "ON COMMIT PRESERVE ROWS" (which sounds appropriate, based on your description) the the data will automatically be deleted when you end the database session.
    All data in Global Temporary Tables is session-specific. If two (or more) people are using the same table at the same time, each will only see the data they inserted themselves; they will never see rows inserted by the other session.
    Almost anything you can do with a regular table you can do with a Global Temporary Table. In particular, DML (such as MERGE) and cursors work exactly as they do on other tables.

  • Can I dropped triggers and recreate them? Dropped is easy but I dont know how to recreate them. I need separate proc to drop and recreate triggers to avoid deadlock issues in package.

    drop  triggers---
    CREATE PROC [dbo].[SP_DropTriggers] 
    AS
    BEGIN
    DECLARE @Table_Triggers SYSNAME, @trName sysname
    DECLARE Cursor_Disabletriggers CURSOR FOR  
    SELECT  object_name(parent_id) , name
    FROM   sys.triggers  
    OPEN Cursor_Disabletriggers
    FETCH NEXT FROM   Cursor_Disabletriggers   
    INTO @Table_Triggers  ,@trname
    DECLARE @SQL nvarchar(max)
    WHILE @@FETCH_STATUS = 0   
    BEGIN  
    SET @SQL  = 'drop trigger ' + 'dbo.'+@trname + ' on dbo.'+@Table_Triggers
    select @sql
    EXECUTE (@SQL)
    FETCH NEXT FROM   Cursor_Disabletriggers INTO @Table_Triggers  ,@trname
    END  
    CLOSE Cursor_Disabletriggers
    DEALLOCATE Cursor_Disabletriggers
    END
    I would like to recreate them in separate proc, How can I achieve this?

    You need a permanent table to store the trigger code in:
    create table
    dbo.TriggerDefinitions
    (TableName nvarchar(128) not null,
    TriggerName nvarchar(128) not null,
    TriggerDefinition nvarchar(max) not null,
    constraint PK_TriggerDefinitions primary key (TableName, TriggerName))
    go
    In your procedure which drops the triggers you need to add code that stores the latest trigger definitions in the table above:
    create procedure dbo.DropTriggers
    as
    begin
    declare @TableName nvarchar(128),
    @TriggerName nvarchar(128),
    @TriggerDefinition nvarchar(max),
    @DynamicSQL nvarchar(max)
    declare TriggerCursor
    cursor fast_forward for
    select quotename(object_schema_name(po.object_id)) + '.' + quotename(po.name),
    quotename(object_schema_name(co.object_id)) + '.' + quotename(co.name),
    m.definition
    from sys.sql_modules as m
    join sys.objects as co
    join sys.objects as po
    on po.object_id = co.parent_object_id
    on co.object_id = m.object_id
    where co.type = 'tr'
    open TriggerCursor
    fetch next
    from TriggerCursor
    into @TableName,
    @TriggerName,
    @TriggerDefinition
    while @@fetch_status = 0
    begin
    if exists(select top 1 1 from TriggerDefinitions where TableName = @TableName and TriggerDefinition = @TriggerDefinition)
    update TriggerDefinitions
    set TriggerDefinition = @TriggerDefinition
    where TableName = @TableName
    and TriggerName = @TriggerName
    else
    insert TriggerDefinitions
    values (@TableName, @TriggerName, @TriggerDefinition)
    if @@rowcount = 1
    begin
    set @DynamicSQL = 'drop trigger ' + @TriggerName + ' on ' + @TableName
    print @DynamicSQL
    --execute sp_executesql
    -- @DynamicSQL
    end
    fetch next
    from TriggerCursor
    into @TableName,
    @TriggerName,
    @TriggerDefinition
    end
    close TriggerCursor
    deallocate TriggerCursor
    end
    go
    Finally the procedure which will re-create the triggers will simply query the table created and populated above and execute the code contained therein.
    create procedure dbo.CreateTriggers
    as
    begin
    declare @TableName nvarchar(128),
    @TriggerName nvarchar(128),
    @TriggerDefinition nvarchar(max),
    @DynamicSQL nvarchar(max)
    declare TriggerCursor
    cursor fast_forward for
    select *
    from dbo.TriggerDefinitions
    open TriggerCursor
    fetch next
    from TriggerCursor
    into @TableName,
    @TriggerName,
    @TriggerDefinition
    while @@fetch_status = 0
    begin
    set @DynamicSQL = @TriggerDefinition
    print @DynamicSQL
    --execute sp_executesql
    -- @DynamicSQL
    fetch next
    from TriggerCursor
    into @TableName,
    @TriggerName,
    @TriggerDefinition
    end
    close TriggerCursor
    deallocate TriggerCursor
    end
    go
    I've commented out the code which actually runs the dynamically created SQL.  You'll have to uncomment those lines for the code I've posted will work.

  • Create Dates table as stored procedure

    I want to modify this statement to use todays date as the start date and add 50 years to insert into table instead of entering a date range and execute it as a stored procedure. Can someone help me to modify this? Thanks
    /**Drop Tables*/
    DROP TABLE [dbo].[DimDate]
    GO
    /** Create Date Dimension Table **/
    /* Create First numbers table for key generation */
    CREATE TABLE Numbers_Small (Number INT);
    INSERT INTO Numbers_Small
    VALUES (0)
    ,(1)
    ,(2)
    ,(3)
    ,(4)
    ,(5)
    ,(6)
    ,(7)
    ,(8)
    ,(9);
    GO
    /* Create Second numbers table for key generation */
    CREATE TABLE Numbers_Big (Number_Big BIGINT);
    INSERT INTO Numbers_Big (Number_Big)
    SELECT (tenthousands.number * 10000 + thousands.number * 1000 + hundreds.number * 100 + tens.number * 10 + ones.number) AS number_big
    FROM numbers_small tenthousands
    ,numbers_small thousands
    ,numbers_small hundreds
    ,numbers_small tens
    ,numbers_small ones;
    GO
    /* Create Date Dimension Table */
    CREATE TABLE [dbo].[DimDate] (
    [DateKey] [int] NOT NULL
    ,[Date] [datetime] NOT NULL
    ,[Day] [char](10) NULL
    ,[DayOfWeek] [smallint] NULL
    ,[DayOfMonth] [smallint] NULL
    ,[DayOfYear] [smallint] NULL
    ,[PreviousDay] [datetime] NULL
    ,[NextDay] [datetime] NULL
    ,[WeekOfYear] [smallint] NULL
    ,[Month] [char](10) NULL
    ,[MonthOfYear] [smallint] NULL
    ,[QuarterOfYear] [smallint] NULL
    ,[Year] [int] NULL
    GO
    /* Create Date Key and Date Fields */
    INSERT INTO [DimDate] (
    DateKey
    ,DATE
    SELECT number_big
    ,DATEADD(day, number_big, '1900-01-01') AS DATE
    FROM numbers_big
    WHERE DATEADD(day, number_big, '1900-01-01') BETWEEN '1900-01-01'
    AND '2050-12-31'
    ORDER BY number_big;
    GO
    /* Update all other fields with appropriate data. */
    UPDATE [DimDate]
    SET Day = DATENAME(DW, DATE)
    ,DayOfWeek = DATEPART(WEEKDAY, DATE)
    ,DayOfMonth = DAY(DATE)
    ,DayOfYear = DATEPART(DY, DATE)
    ,PreviousDay = DATEADD(DAY, - 1, DATE)
    ,NextDay = DATEADD(DAY, 1, DATE)
    ,WeekOfYear = DATEPART(WK, DATE)
    ,Month = DATENAME(MONTH, DATE)
    ,MonthOfYear = MONTH(DATE)
    ,QuarterOfYear = DATEPART(Q, DATE)
    ,Year = YEAR(DATE);
    GO
    /* Drop Temp Tables */
    DROP TABLE Numbers_Small;
    DROP TABLE Numbers_Big;

    SQL is a database language, so why do you want to re-compute constant data over and over, hundreds of times a day for years? UGH! 
    There are 365.2422 days per year, so a century of calender data is only 36,525 rows! Maybe 40 bytes per row? About 1.5 Kbytes  total? This will fit into main storage
    What you did post was wrong. DATE is a reserved word in SQL and it is  unit of temporal measurement. You also seem to confuse columns and fields. In SQL a field is a sub-unit of a temporal measurement (YEARS, MONTH, DAY, HOUR, MINUTE, SECOND). Please
    learn the ISO-11179 rules for data element names.
    You crammed too much in the table. The new DATE data type is only 3 bytes! Your other columns are mostly redundant and have attribute splitting problems.  Try this:
    CREATE TABLE Calendar 
    (cal_date DATE NOT NULL PRIMARY KEY,
     julian_date INTEGER NOT NULL, 
     julian_business_day INTEGER NOT NULL, 
     ordinal_date CHAR(8) NOT NULL
       CHECK (ordinal_date 
           LIKE '[12][0-9][0-9][0-9]-[0-9][0-9][0-9]') NOT NULL,
     week_date CHAR(9) NOT NULL
        CHECK (week_date LIKE '[12][0-9][0-9][0-9]W[0-5][0-9]-[0-7])
    The julianized date is a sequential number over the whole calendar. It makes temporal math easier. 
    ISO-8601 week_date is the week-within-year. This format is 'yyyyWww-d' where yyyy is the year, W is a separator token, ww is (01-53) week number and d is (1-7) day of the week. 
    There are several websites with calendars you can cut & paste, but you can start your search with: http://www.calendar-365.com/week-number.html 
    The Julian business day is a good trick. Number the days from whenever your calendar starts and repeat a number for a weekend or company holiday. 
    CREATE TABLE Calendar
    (cal_date DATE NOT NULL PRIMARY KEY, 
     julian_business_nbr INTEGER NOT NULL, 
    INSERT INTO Calendar 
    VALUES ('2007-04-05', 42), 
     ('2007-04-06', 43), -- good Friday 
     ('2007-04-07', 43), 
     ('2007-04-08', 43), -- Easter Sunday 
     ('2007-04-09', 44), 
     ('2007-04-10', 45); --Tuesday
    To compute the business days from Thursday of this week to next
     Tuesdays:
    SELECT (C2.julian_business_nbr - C1.julian_business_nbr)
      FROM Calendar AS C1, Calendar AS C2
     WHERE C1.cal_date = '2007-04-05',
       AND C2.cal_date = '2007-04-10'; 
    Why store things like the month name in the table? This is a display field, not a schema column value. It is language dependent! It is only part of a scalar value, too; why not normalize? 
    But if you need them, then use computed columns that are not materialized until needed. Also, use the SUBSTRING() for things that are not numeric. Why use SMALLINT for the day of the week?  Are you going to divide Thursday by 42? It is a name, not a numeric. 
    You saw the tricks with a Series table wanted to use them, but do not  be the boy with a new hammer who thinks everything is a nail. I find that a spreadsheet is the best way to create such a calendar table because they have so many temporal options and
    functions. 
    Also, putting the comma at the start of  a line is an old punchcard trick that we do not use any more. Back in the 1960's, it let us re-arrange the deck and re-use the cards. All it cost us was readable code –- your eyes expect to see a comma after a string,
    so this makes a twitch as you read. 
    --CELKO-- Books in Celko Series for Morgan-Kaufmann Publishing: Analytics and OLAP in SQL / Data and Databases: Concepts in Practice Data / Measurements and Standards in SQL SQL for Smarties / SQL Programming Style / SQL Puzzles and Answers / Thinking
    in Sets / Trees and Hierarchies in SQL

Maybe you are looking for