Stored procedure to insert into multiple tables in sql server 2012, using id col from one table to insert into the other 2

Hi all,
Apologies if any of the following sounds at all silly but I am fairly new to this so here goes...
I have 3 tables that require data insertion at the same time. The first table is the customers table, I then want to take the automatically generated custid from that table and inser it into 2 other tables along with some other data
Here's what I have so far which does not work:
CREATE PROCEDURE CustomerDetails.bnc_insNewRegistration @CustId int,
@CompanyName varchar(100),
@FirstName varchar(50),
@LastName varchar(50),
@Email nvarchar(254),
@HouseStreet varchar(100),
@Town smallint,
@County tinyint,
@Postcode char(8),
@Password nvarchar(20)
AS
BEGIN
begin tran
insert into CustomerDetails.Customers
(CompanyName, FirstName, LastName, EmailAddress)
Values (@CompanyName, @FirstName, @LastName, @Email)
set @CustId = (select CustId from inserted)
insert into CustomerDetails.Address
(CustomerId, HouseNoAndStreet, Town, County, PostCode)
values (@CustId, @HouseStreet, @Town, @County, @Postcode)
insert into CustomerDetails.MembershipDetails
(CustomerId, UserName, Password)
values (@CustId, @Email, @Password)
commit tran
END
GO
If anyone could help with this I would very much appreciate it as I am currently building an online store, if there's no registration there's no customers.
So to whom ever is able to help, I thank you whole heartedly :)

I hope by now it is apparent that statements like "doesn't work" are not particularly helpful. The prior posts have already identified your first problem.  But there are others.  First, you have declared @CustID as an argument for your
procedure - but it is obvious that you do not expect a useful value to be supplied when the procedure is executed.  Perhaps it should be declared as an output argument so that the caller of the procedure can know the PK value of the newly inserted customer
- otherwise, replace it with a local variable since it serves no purpose as an input argument.
Next, you are storing email twice.  Duplication of data contradicts relational theory and will only cause future problems. 
Next, I get the sense that your "customer" can be a person or a company.  You may find that using the same table for both is not the best approach.  I hope you have constraints to prevent a company from having a first and last name (and
vice versa).
Next, your error checking is inadequate.  We can only hope that you have the appropriate constraints to prevent duplicates.  You should expect failures to occur, from basic data errors (duplicates, null values, inconsistent values) to system issues
(out of space).  I'll leave you with Erland's discussion for more detail:
erland - error handling.
Lastly, you should reconsider the datatypes you are using for the various bits of information.  Presumably town and county are foreign keys to related tables, which is why they are numeric.  Be careful you don't paint yourself into a corner with
such small datatypes.  One can also debate the wisdom of using a separate tables for Town and County (and perhaps the decision to limit yourself to a particular geographic area with a particular civic hierarchy). Password seems a little short to me. 
And if you are going to use nvarchar for some strings, you might as well use it for everything - especially names.  Also, everyone should be security conscious by now - passwords should be encrypted at the very least.
And one last comment - you really should allow 2 address lines. Yes, two separate ones and not just one much larger one.

Similar Messages

  • Read Oracle 10g Tables to SQL Server 2012

    Hi all,
    I have Oracle 10g on an XP machine, and use the 'Oracle in OraDB10g_home1' driver to read the data. I have another Windows Server 2008 R2 machine on the same network, with SQL Server 2012 on it. What is the best way to read Oracle Tables in SQL Server? Can I setup an ODBC link from my Windows Server machine to the Oracle Database (which would require me to download an Oracle ODBC driver)? Or is the best way to export the required tables from Oracle (e.g. into csv format) and import them into SQL?
    Thanking you in advance,
    Imelda.

    987575 wrote:
    Hi all,
    I have Oracle 10g on an XP machine, and use the 'Oracle in OraDB10g_home1' driver to read the data. I have another Windows Server 2008 R2 machine on the same network, with SQL Server 2012 on it. What is the best way to read Oracle Tables in SQL Server? Can I setup an ODBC link from my Windows Server machine to the Oracle Database (which would require me to download an Oracle ODBC driver)? Or is the best way to export the required tables from Oracle (e.g. into csv format) and import them into SQL?
    Thanking you in advance,
    Imelda.You should use Heterogeneous Services
    Following is a demonstration in ASKTOM to connect from Oracle to Excel, You can use the same to connect to SQL Server.
    http://asktom.oracle.com/pls/apex/f?p=100:11:0::::P11_QUESTION_ID:4406709207206#18830681837358

  • SQL Server synonym used in two ways, local table and Oracle table via ODBC, fails on ODBC

    I am implementing a Web Site at our institution that was written for another institution that was all SQL Server.The Web Site has included as a feature the use of synonyms which have a dual use. Normally they point to a different machine, different database (PeopleSoft)
    via linked server, but if the linked server connection fails they can be switched to point to tables on the local instance by running a stored procedure that redefines the synonyms. This is a failover feature meant to keep the site up by resorting to
    possibly out of date data if need be.
    This means that any SQL Select statement that uses one of these synonyms is unaware of whether the data returned comes from the local instance or from another remote instance. There is no logic to check whether the linked server is functioning or not.
    The local instance is a custom SQL Server database at both institutions. The remote instance is one of two PeopleSoft instances at both shops; however, while the original website was written to work with the remote instance being SQL Server,
    our shop uses Oracle for PeopleSoft. This means that our linked servers are further complicated by an ODBC connection that the original site did not need.
    The problem I have is that the SQL statements in the stored procedures that came with the Web Site do not work when a synonym is used that points to the remote PeopleSoft instance. The same statements also fail in SSMS.  I get this error when I run
    this statement (select * from PS_ZZ_BUD_JOB_VW):
    Error: The OLE DB provider "OraOLEDB.Oracle" for linked server "CSUPG" does not contain the table
         ""dbo"."PS_ZZ_BUD_JOB_VW"". The table either does not exist or the current user does not have  permissions on that table.
    I can successfully query the PeopleSoft database using openquery, but unless I can get the synonyms to work as they were intended to, I'll have to rewrite all the stored procedures that use them to: 1) check if the linked servers are up, then 2) execute
    one of two versions of each SQL statement depending on the result of that check.

    Will the four-part notation work when the synonym is pointing to the local SQL Server table ?
    You should not use four-part notation when you reference your synonym. The four-part query that I suggested is only one you would to determine to define our synonym correctly when the view is on the Oracle server.
    In the case of synonym PS_ZZ_BUD_JOB_VW, it can point to either an Oracle view of the same name, or to a local SQL Server table named PS_HR_JOB.
    Then the table is local the synonuym definition should be
    CREATE SYNONYM PS_ZZ_BUD_JOB_VW FOR dbo.PS_HR_JOB
    Erland Sommarskog, SQL Server MVP, [email protected]

  • Getting Changed [Status] rows between multiple rows in SQL Server 2012 based on MonthYear Field

    I am trying create Stored Proc which takes 2 inputs from user  @PreviousMonthYear,@CurrentMonthYear
    Below is my table schema.[TableIPPortStatus]
    Such 1000's of rows will be available in TableIPPortStatus for every IP Port combination for every Scan. Stored Proc will take input as @PreviousMonthYear = 'Jan-2013' and @CurrentMonthYear = 'Feb-2013'
    Expected stored proc o/p is to get changed status in @CurrentMonthYear rows compared with the same IP/Port combination from @PreviousMonthYear rows. so for for above e.g. expecting to get below result.
    Since in Scan 2222 Port 80 of IP 1.0.0.0 got closed & Port 80 of IP 1.0.0.1 got open and for 1.0.0.2 status was unchanged.
    Also, if any new IPPort combination is added in Feb-2013 that needs to make available in the output.
    Please suggest way to accomplish this in SQL. Thanks in Advance!

    DId you try this? ACtually you dont even need prevmonthyear parameter. you can simply get result using single parameter
    If its sql 2012 this is very easy
    DECLARE @CurrentMonthYear varchar(30)
    SET @CurrentMonthYear = 'Feb-2013'
    SELECT ScanId,MonthYear,IP,Port,Status
    FROM
    SELECT *,
    LAG(Status,1,'') OVER (PARTITION BY IP,Port ORDER BY CAST('01-' + MonthYear AS datetime)) AS PrevStatus
    FROM Table
    )t
    WHERE PrevStatus <> Status
    And if its sql 2008 or below
    DECLARE @CurrentMonthYear varchar(30)
    SET @CurrentMonthYear = 'Feb-2013'
    ;With CTE
    AS
    SELECT *,
    ROW_NUMBER() OVER (PARTITION BY IP,Port ORDER BY CAST('01-' + MonthYear AS datetime)) AS Seq
    FROM Table
    WHERE MonthYear = @CurrentMonthYear
    )t
    SELECT c1.*
    FROM CTE c1
    LEFT JOIN CTE c2
    ON c2.IP = c1.IP
    AND c2.Port = c1.Port
    AND c2.Seq = c1.Seq - 1
    WHERE c2.Status <> c1.Status
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • Cannot edit an existing table in sql server 2012

    Exception has been thrown by the target of an invocation. (SQLEditors)
    ADDITIONAL INFORMATION:
    The 'DbProviderFactories' section can only appear once per config file. (System.Configuration)
    I was trying to design a table and it threw this exception.
    Exception has been thrown by the target of an invocation. (SQLEditors)
    ADDITIONAL INFORMATION:
    Unable to find the requested .Net Framework Data Provider.  It may not be installed. (System.Data)
    What am I missing? Do I need to download something?

    Hi Geoff33,
    According to the error messages, it might be caused by that there are duplicate <DbProviderFactories> tags in the machine.config files. As Satish’s post, please remove empty element DbProviderFactories in the following files.
    C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG\machine.config
    C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\machine.config
    However, if the error still occurs after that, it might be caused by that the SQL Server Management Studio (SSMS) is not installed properly. I recommend you to design the table via Transact-SQL. Alternatively, you can reinstall the client tools from installation
    media.
    Thanks,
    Lydia Zhang

  • SQL Server 2012 Management Studio:Importing XML file to new Table of new Database-XML parsing: unexpected end of input???

    Hi all,
    In the Notepad, I created an xml file (ZenQroducts.xml) :
    <Qroducts>
    <Qroduct>
    <SKU>1</SKU>
    <Desc>Book</Desc>
    </Qroduct>
    <Qroduct>
    <SKU>2</SKU>
    <Desc>DVD</Desc>
    </Qroduct>
    <Qroduct>
    <SKU>3</SKU>
    <Desc>Video</Desc>
    </Qroduct>
    In my SQL Server 2012 Management Studio, I executed the following code:
    --to create a new object Qroducts in a new database OPENXMLtesting
    CREATE DATABASE OPENXMLtesting
    GO
    CREATE TABLE Qroducts(
    sku INT Primary KEY,
    qroduct_desc VARCHAR(30));
    INSERT INTO Qroducts (sku, qroduct_desc)
    SELECT X.qroduct.query('SKU').value('.', 'INT'),
    X.qroduct.query('Desc').value('.', 'VARCHAR(30)')
    FROM (
    SELECT CAST(x AS XML)
    FROM OPENROWSET(
    BULK 'H:\ZenQroducts.xml',
    SINGLE_BLOB) AS T(x)
    ) AS T(x)
    CROSS APPLY x.nodes('Qroducts/Qroduct') AS X(qroduct);
    SELECT sku, qroduct_desc
    FROM Qroducts;
    I got the following message:
    Msg 9400, Level 16, State 1, Line 6
    XML parsing: line 13, character 12, unexpected end of input
    I have no ideas why I got this "XML parsing:line 13, character12, unexpected end of input" message. Please kindly help, advise me on where I made mistake and how I can resolve this problem, and respond in this Forum.
    Thanks in advance,
    Scott Chang
     

    Hi Manish, Thanks for your response.
    Yes, it is a duplicate with Qroducts/Qroduct instead of Products/Product. I did it, because I don't know how to remove the existing "Products" database.
    Again, I got the existing "Qroducts" database in this second trial!!??  I am comletely lost in doing "Importing XML file to SQL Table" now!!  I think that I have not touched T-SQL and XML programming, since 2008. I
    did not catch the new features of T-SQL 2008, XML, SQL/XML, XQuery, etc. for long time. Recently, I did not know what DECLARE, @x, SET,...were, and dived into the SQL/XML and XQuery programming. I knew the SQL Basics (SELECT, FROM, WHERE,..), creating
    the names of databases and tables in SQL Server 2008/2012 Management Studio (Express) before. This morning, I found an old T-SQL 2008 Prgrammer's Guide that has the new features of SQL Server 2008 for T-SQL, XML, XQuery, etc. I just starting reading
    it to know what DECLARE, @x, SET,... are. But, I still don't know where the existing databases "Products" and "Qroducts" (created by me) are - they are not in the Databases of SQL Server 2012 Management Studio I am using!!??  Could
    you please kindly point out where the "Products" and "Qroducts" databases are?
    Prashanth responded to my posted question too and he asked to to try his code: DECLARE @xml XML, SELECT @xml =' <Qroducts>.....SELECT product.value.....FROM @XML.nodes.....AS.... I just learned that his code is doing the thing we
    want to do and print the results below the SQL Query. This is not what I need in doing my SQL/XML programming. I am reading/studying the new (2008) features of T-SQL, XQuery 1.0: An XML Query Language (Second Edition), and Microsoft XQuery Language Reference
    (SQL Server 2012 Books Online) closely now. I hope that I can resume the T-SQL, XML Query, SQL/XML, XQuery in my SQL Server 2012 Management Studio soon.
    Please tell me  where the existing databases "Products" and "Qroducts" I created in my previous trials in my SQL Server 2012 Management Studio.  This is what I need to know and to delete them, before I do this kind of "Importing
    XML file to Table of SQL Server 2012 Management Studio"  programming again.
    Please kindly help, advise and respond again.
    Many Thanks,
    Scott Chang

  • Ssis - import data from flat file to table (sql server 2012)

    i have create a ssis for importing data from flat file to table in sql server 2012.
    but i got the below error for some column in data flow task.
    error: cannot processed because than one code page (950 and 1252)
    anyone helps~

    Hi,
    The issue occurs because the source flat file uses ANSI/OEM – Tranditional Chinese Big5 encoding. When processing the source file, the flat file connection manager uses code page 950 for the columns. Because SQL Server uses code page to perform conversions
    between non-Unicode data and Unicode data, the data in the code page 950 based input columns cannot be loaded to code page 1252 based destination columns. To resolve the issue, you need to load the data into a SQL Server destination table that includes Unicode
    columns (nchar or nvarchar), and convert the input columns to Unicode columns via Data Conversion or the Advanced Editor for the Flat File Source at the same time.
    Another option that may not be that practical is to create a new database based on the Chinese_Taiwan_Stroke_BIN collation, and load the data to non-Unicode columns directly.
    Reference:
    http://social.technet.microsoft.com/Forums/windows/en-US/f939e3ba-a47e-43b9-88c3-c94bdfb7da58/forum-faq-how-to-fix-the-error-the-column-xx-cannot-be-processed-because-more-than-one-code-page?forum=sqlintegrationservices 
    Regards,
    Mike Yin
    TechNet Community Support

  • Best procedure to downgrade a SQL Server 2012 SP2 installation from Enterprise edition to Standard edition

    Hi,
    following a purpose change for a database server, I need to downgrade the SQL Server 2012 SP 2 installation from Enterprise to Standard edition.
    Does it exist the best procedure to do it in a secure manner with a low impact?
    Many thanks

    Please note that while you are downgrading by uninstalling and reinstalling and then restoring backup  taken from 2012 enterprise to standard , if backup contains data about used enterprise features you would not be able to restore the backup so BE
    CAREFUL.
    You should , if possible, get a new box install SQL Server standard and try restoring backup if it fails disable enterprise features and again take backup and then you would be able to restore.
    Please mark this reply as answer if it solved your issue or vote as helpful if it helped so that other forum members can benefit from it
    My Technet Wiki Article
    MVP

  • Inserting data from one table into another table using PL/SQL

    HI,
    I am trying to insert values from one table into another using PL procedure, the values I want to retrieve from the table riverside1 are charac_id and charac_type and insert these values into another table called riverside2 , the stored procedure zorgs_gorfs(x,y) accepts two parameters which are 2 charac_id's of d characters in riverside1 then using insert statements inserts these characters from riverside1 into riverside2.
    CREATE OR REPLACE PROCEDURE zorgs_gorfs(x IN NUMBER, y IN NUMBER) AS
         BEGIN
              INSERT INTO riverside2
                   (charac_id)
              VALUES
                   (x);
    INSERT INTO riverside2
                   (charac_id)
              VALUES
                   (y);
          END zorgs_gorfs;
    /This works but the problem im having is that when I also try to insert the charac_type as well as the charac_id it doesnt work below is the code:
    CREATE OR REPLACE PROCEDURE zorgs_gorfs(x IN NUMBER, y IN NUMBER) AS
         BEGIN
              INSERT INTO riverside2
                   (charac_id,charac_tye)
              VALUES
                   (Select
                        charac_id,
                        charc_type
                   FROM
                        riverside1
                   WHERE
                        charac_id = x);
          END zorgs_gorfs;
    /can someone kindly sort me out

    modify this sql
    INSERT INTO riverside2
                   (charac_id,charac_tye)
              VALUES
                   (Select
                        charac_id,
                        charc_type
                   FROM
                        riverside1
                   WHERE
                        charac_id = x);as
    INSERT INTO riverside2
                   (charac_id,charac_tye)
              VALUES
                   (Select
                        charac_id,
                        charc_type
                   FROM
                        riverside1
                   WHERE
                        charac_id in ( x,y));But my suggestion would be consider revising your approach. It does not look that good.
    Thanks,
    karthick.

  • How to get the data from one table and insert into another table

    Hi,
    We have requirement to build OA page with the data needs to be populated from one table and on save data into another table.
    For the above requirement what the best way to implement in OAF.
    I understand that if we attach VO object instance to region/page, we only can pull and put data in to only one table.
    Thanks

    You can achieve this in many different ways, one is
    1. Create another VO based on the EO which is based on the dest table.
    2. At save, copy the contents of the source VO into the dest VO (see copy routine in dev guide).
    3. commiting the transaction will push the data into the dest table on which the dest VO is based.
    I understand that if we attach VO object instance to region/page, we only can pull and put data in to only one table.
    if by table you mean a DB table, then no, you can have a VO based on multiple EOs which will do DMLs accordingly.Thanks
    Tapash

  • SQL Server 2012 Management Studio: Creating a Database and a dbo Table. Inserting VALUES into the table. How to insert 8 Values for future use in XQuery?

    Hi all,
    In my SQL Server 2012 Management Studio (SSMS2012), I tried to create a Database (MacLochainnsDB) and a dbo Table (marvel). then I wanted insert 8 VALUES into the Table by using the following code:
    USE master
    IF EXISTS
    (SELECT 1
    FROM sys.databases
    WHERE name = 'MacLochlainnsDB')
    DROP DATABASE MacLochlainnsDB
    GO
    CREATE DATABASE MacLochlainnsDB
    GO
    CREATE TABLE [dbo].[marvel] (
    [avenger_name] [char] (30) NULL)
    INSERT INTO marvel
    (avenger_name)
    VALUES
    ('Hulk', 1),
    ('Iron Man', 2),
    ('Black Widow', 3),
    ('Thor', 4),
    ('Captain America', 5),
    ('Hawkeye', 6),
    ('Winter Soldier', 7),
    ('Iron Patriot', 8)
    I got the following error Message:
    Msg 110, Level 15, State 1, Line 5
    There are fewer columns in the INSERT statement than values specified in the VALUES clause. The number of values in the VALUES clause must match the number of columns specified in the INSERT statement.
    How can I correct this problem?
    Please kindly help and advise.
    Thanks in advance,
    Scott Chang
    P. S.
    The reason I tried to create the Database, dbo Table, and then to insert the VALUES is to learn the following thing:
    You can query the entire node tree with the following xquery statement because it looks for the occurrence of any node with the /* search string:
    DECLARE @x xml;
    SET @x = N'<marvel>
    <avenger_name>Captain America</avenger_name>
    </marvel>';
    SELECT @x.query('/*');
    You can query the avenger_name elements from the marvel_xml table with the following syntax:
    SELECT xml_table.query('/marvel/avenger_name')
    FROM marvel_xml;
    It returns the following set of avenger_name elements:
    <avenger_name>Hulk</avenger_name>
    <avenger_name>Iron Man</avenger_name>
    <avenger_name>Black Widow</avenger_name>
    <avenger_name>Thor</avenger_name>
    <avenger_name>Captain America</avenger_name>
    <avenger_name>Hawkeye</avenger_name>
    <avenger_name>Winter Soldier</avenger_name>
    <avenger_name>Iron Patriot</avenger_name>
    You can query the fourth avenger_name element from the marvel_xml table with the following xquery statement:
    SELECT xml_table.query('/marvel[4]/avenger_name')
    FROM marvel_xml;
    It returns the following avenger_name element:
    <avenger_name>Thor</avenger_name>

    Hi Scott,
    The master database records all the system-level information for a SQL Server system, so best practise would be not to create any user-defined
    object within it.
    To change your default database(master by default) of your login to another, follow the next steps so that next time when connected you don't have to use "USE dbname" to switch database.
    Open SQL Server Management Studio
    --> Go to Object explorer(the left panel by default layout)
    --> Extend "Security"
    --> Extend "Logins"
    --> Right click on your login, click "propertites"
    --> Choose the "Default database" at the bottom of the pop-up window.
    --or simply by T-SQL
    Exec sp_defaultdb @loginame='yourLogin', @defdb='youDB'
    Regarding your question, you can reference the below.
    SELECT * FROM master.sys.all_objects where name ='Marvel'
    --OR
    SELECT OBJECT_ID('master.dbo.Marvel') --if non empty result returns, the object exists
    --usually the OBJECT_ID is used if a if statement as below
    IF OBJECT_ID('master.dbo.Marvel') IS NOT NULL
    PRINT ('TABLE EXISTS') --Or some other logic
    What is the sys.all_objects? See
    here.
    If you have any question, feel free to let me know.
    Eric Zhang
    TechNet Community Support

  • How to extract data from multiple flat files to load into corresponding tables in SQL Server 2008 R2 ?

    Hi,
              I have to implement the following scenario in SSIS but don't know how to do since I never worked with SSIS before. Please help me.
              I have 20 different text files in a single folder and 20 different tables corresponding to each text file in SQL Server 2008 R2 Database. I need to extract the data from each text file and
    load the data into corresponding table in Sql Server Database. Please guide me in how many ways I can do this and which is the best way to implement this job.  Actually I have to automate this job. Few files are in same format(with same column names
    and datatypes) where others are not.
    1. Do I need to create 20 different projects ?
                   or
        Can I implement this in only one project by having 20 packages?
                 or
        Can I do this in one project with only one package?
    Thanks in advance.

    As I said I don't know how to use object data type, I just given a shot as below. I know the following code has errors can you please correct it for me.
    Public
    Sub Main()
    ' Add your code here 
    Dim f1
    As FileStream
    Dim s1
    As StreamReader
    Dim date1
    As
    Object
    Dim rline
    As
    String
    Dim Filelist(1)
    As
    String
    Dim FileName
    As
    String
    Dim i
    As
    Integer
    i = 1
    date1 =
    Filelist(0) =
    "XYZ"
    Filelist(1) =
    "123"
    For
    Each FileName
    In Filelist
    f1 = File.OpenRead(FileName)
    s1 = File.OpenText(FileName)
    rline = s1.ReadLine
    While
    Not rline
    Is
    Nothing
    If Left(rline, 4) =
    "DATE"
    Then
    date1 (i)= Mid(rline, 7, 8)
     i = i + 1
    Exit
    While
    End
    If
    rline = s1.ReadLine
    End
    While
    Next
    Dts.Variables(
    "date").Value = date1(1)
    Dts.Variables(
    "date1").Value = date1(2)
    Dts.TaskResult = ScriptResults.Success
    End
    Sub

  • Insert old missing data from one table to another(databaase trigger)

    Hello,
    i want to do two things
    1)I want to insert old missing data from one table to another through a database trigger but it can't be executed that way i don't know what should i do in case of replacing old data in table_1 into table_2
    2)what should i use :NEW. OR :OLD. instead.
    3) what should i do if i have records exising between the two dates
    i want to surpress the existing records.
    the following code is what i have but no effect occured.
    CREATE OR REPLACE TRIGGER ATTENDANCEE_FOLLOWS
    AFTER INSERT ON ACCESSLOG
    REFERENCING NEW AS NEW OLD AS OLD
    FOR EACH ROW
    DECLARE
    V_COUNT       NUMBER(2);
    V_TIME_OUT    DATE;
    V_DATE_IN     DATE;
    V_DATE_OUT    DATE;
    V_TIME_IN     DATE;
    V_ATT_FLAG    VARCHAR2(3);
    V_EMP_ID      NUMBER(11);
    CURSOR EMP_FOLLOWS IS
    SELECT   EMPLOYEEID , LOGDATE , LOGTIME , INOUT
    FROM     ACCESSLOG
    WHERE    LOGDATE
    BETWEEN  TO_DATE('18/12/2008','dd/mm/rrrr') 
    AND      TO_DATE('19/12/2008','dd/mm/rrrr');
    BEGIN
    FOR EMP IN EMP_FOLLOWS LOOP
    SELECT COUNT(*)
    INTO  V_COUNT
    FROM  EMP_ATTENDANCEE
    WHERE EMP_ID    =  EMP.EMPLOYEEID
    AND    DATE_IN   =  EMP.LOGDATE
    AND    ATT_FLAG = 'I';
    IF V_COUNT = 0  THEN
    INSERT INTO EMP_ATTENDANCEE (EMP_ID, DATE_IN ,DATE_OUT
                                ,TIME_IN ,TIME_OUT,ATT_FLAG)
         VALUES (TO_NUMBER(TO_CHAR(:NEW.employeeid,99999)),
                 TO_DATE(:NEW.LOGDATE,'dd/mm/rrrr'),       -- DATE_IN
                 NULL,
                 TO_DATE(:NEW.LOGTIME,'HH24:MI:SS'),      -- TIME_IN
                 NULL ,'I');
    ELSIF   V_COUNT > 0 THEN
    UPDATE  EMP_ATTENDANCEE
        SET DATE_OUT       =  TO_DATE(:NEW.LOGDATE,'dd/mm/rrrr'), -- DATE_OUT,
            TIME_OUT       =   TO_DATE(:NEW.LOGTIME,'HH24:MI:SS'), -- TIME_OUT
            ATT_FLAG       =   'O'
            WHERE EMP_ID   =   TO_NUMBER(TO_CHAR(:NEW.employeeid,99999))
            AND   DATE_IN <=  (SELECT MAX (DATE_IN )
                               FROM EMP_ATTENDANCEE
                               WHERE EMP_ID = TO_NUMBER(TO_CHAR(:NEW.employeeid,99999))
                               AND   DATE_OUT IS NULL
                               AND   TIME_OUT IS NULL )
    AND   DATE_OUT  IS NULL
    AND   TIME_OUT IS NULL  ;
    END IF;
    END LOOP;
    EXCEPTION
    WHEN OTHERS THEN RAISE;
    END ATTENDANCEE_FOLLOWS ;
                            Regards,
    Abdetu..

    INSERT INTO SALES_MASTER
       ( NO
       , Name
       , PINCODE )
       SELECT SALESMANNO
            , SALESMANNAME
            , PINCODE
         FROM SALESMAN_MASTER;Regards,
    Christian Balz

  • Need To Create a table in Sql Server and do some culculation into the table from Oracle and Sql

    Hello All,
    I'm moving a data from Oracle to Sql Server with ETL (80 tables with data) and i want to track the number of records that i moving on the daily basis , so i need to create a table in SQL Server, wilth 4 columns , Table name, OracleRowsCount, SqlRowCount,
    and Diff(OracleRowsCount - SqlRowCount) that will tell me the each table how many rows i have in Oracle, how many rows i have in SQL after ETL load, and different between them, something like that:
    Table Name  OracleRowsCount   SqlRowCount  Diff
    Customer                150                 150            
    0
    Sales                      2000                1998          
    2
    Devisions                 5                       5             
    0
    (I can add alot of SQL Tasks and variables per each table but it not seems logicly to do that, i tryid to find a way to deal with that in vb but i didn't find)
    What the simplest way to do it ?
    Thank you
    Best Regards
    Daniel

    Hi Daniel,
    According to your description, what you want is an indicator to show whether all the rows are inserted to the destination table. To achieve your goal, you can add a Row Count Transformation following the OLE DB Destination, and redirect bad rows to the Row
    Count Transformation. This way, we can get the count of the bad rows without redirecting these rows. Since the row count value is stored in a variable, we can create another string type variable to retrieve the row count value from the variable used by the
    Row Count Transformation, and then use a Send Mail Task to send the row count value in an email message body. You can also insert the row count value to the SQL Server table through Execute SQL Task. Then, you can check whether bad rows were generated in the
    package by querying this table.  
    Regards,
    Mike Yin
    TechNet Community Support

  • Creation of System Stored Procedure in SQL Server 2012 & SQL Server 2012 R2.

    Hi all,
    I am stuck at a point I am looking for a system stored procedure named 'sp_dboption' in SQL Server 2012  & R2 but could not find.
    Searched for it on the net and found that, this stored procedure 'sp_dboption' is now obsolete. So I tried to copy the content of 'sp_dboption' stored procedure from SQL Server 2008 R2 and create new system stored procedure with this name 'sp_dboption' in
    SQL Server 2012 but was unable to create the system stored procedure.
    Can you guys please tell me how to create system stored procedure in SQL Server 2012 & SQL Server 2012 R2. The reason of why I want to achieve this is because I have used 'sp_dboption' system stored procedure  in my application to create a database.
    As 'sp_dbotion' stored procedure is present in SQL Server 2008 R2 I am able to create the database in SQL server 2008 R2 but not in SQL server 2012.
    Can you please guide me how to create system stored procedure. I am out of luck.
    Please assist me, thanks & looking for help at the earliest. Hope someone will come to the fore and help me.

    Hi Vishwajeet,
    If you tried to create any object in the sys schema, you will get the error below.
    The specified schema name "sys" either does not exist or you do not have permission to use it.
    So I am afraid creating any object in sys schema is not supported by SQL Server. Here is a similar link for your reference.
    How to create table in SYS schema in SQL Server?
    Though sp_dboption is not in SQL Server 2012, does creating a user-defined one with the same content in 2008 make any difference in your business? You just need to specify the fully qualified name dbname.dbo.sp_dboption.
    If you are still interested in creating a system sp_dboption, you can register it with the
    sp_ms_marksystemobject.
    See
    Creating Your Own SQL Server System Stored Procedures.
    Eric Zhang
    TechNet Community Support

Maybe you are looking for

  • HELP!!! layer 0 exceeds the maximum layer size allowed (DVD STUDIO PRO)

    when I try to burn a dual dvd with 7.1 gb on it. The discs are 8.5gb dual dvd's, it says this in the error box. Formatting was not successful. Layer 0 exceeds the maximum layer size allowed. Please choose a suitable marker location that will support

  • Ios7 how to delete bookmarks?

    My bookmarks are still there after the download which I definitely wish I had not done!  There appear to be no way of deleting unwanted bookmarks. I have even looked in ios7 manual and there is nothing about deleting them only adding them?

  • Problem regarding saving ibots

    hi...good evening... I am setting up ibots for BI Analytics in solaris server.. I have successfully ran all the steps... 1)createing S_NQ tables 2)configuring the job manager 3)configuring the scheduler etc etc. also i have ran the cryptotools and al

  • Quicktime 7.6.6 problems

    I have been having a problem with Quicktime Pro 7.6.6 for about a month (previous versions have worked with out problems). The problem is that Quicktime requires administrative permission to run when UAC is enabled. As a result, "right click" to play

  • Route Determinaiton based on shipping instructions.

    Hi Experts, I wanted to determine the route based on shipping instruction. How I can bring the shipping instruction field in route determination instead of shipping condition. Our current process is, route determination based on shipping condition bu