How to avoid or replace a sub query from Exists statement.

Hello all,
I have a query regarding sql query.
DB 1
Table A                                 Table B
ID   Code   HeaderID            ID   
1    100      1                          1
2    200      1                          2
3    100      2                          3
DB 2
Table C
ID    Code  Type
1     100     1
2     101     1
3     100     2
set @HeaderID = 1
IF EXISTS (SELECT Code From Table A WHERE HeaderID=@ID AND Code  not in (SELECT Code FROM Table C WHERE Type=1))
BEGIN
RAISERROR('code is not set.',16,1)
END
Table A and Table C are in different databases say DB1 and DB2.
How can we replace this with another query using join or something. Can we do it using one query by avoiding sub query.I want to get Code 200 which is not match with Table C Code.
Regards, Ranjith T Rajan Acty System India Pvt Ltd.

Instead of checking later and raising an error you can create a check constraint on the table so that it raises error when you insert the non existent code itself.
You can create a UDF like below
CREATE FUNCTION CheckCodeExistence
@Code int,
@HeaderID int
RETURNS bit
AS
BEGIN
DECLARE @Ret bit
SELECT @Ret = CASE WHEN NOT EXISTS (SELECT 1
FROM DB2.dbo.TableC
WHERE Code = @code
AND [TYPE] = @headerID)
THEN 0
ELSE 1 END
RETURN(@ret)
END
Then create a check constraint on Table A based on it as
ALTER TABLE TableA ADD CONSTRAINT Chk_TableA CHECK (dbo.CheckCodeExistence(Code,HeaderID) =1 )
Now when you try to insert record with Code 200 you'll get the below
Msg 547, Level 16, State 0, Line 1
The INSERT statement conflicted with the CHECK constraint "Chk_TableA". The conflict occurred in database "DB1", table "dbo.TableA".
The statement has been terminated.
See similar example here
http://visakhm.blogspot.in/2012/05/implementing-multiple-table-based-check.html
Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

Similar Messages

  • How to make outer join in Sub Query?

    Hi!
    I'm facing one problem. Can anyone tell me - how to make outer join in sub query?
    I'm pasting one sample code -
    select e.empno, e.ename,e.job,e.sal,d.deptno,d.dname
    from d_emp e, d_dept d
    where e.deptno(+) = (
                          case
                            when d_dept.deptno = 10
                              then
                                  select deptno
                                  from d_dept
                                  where dname = 'SALES'
                          else
                            d_dept.deptno
                          end
    SQL>
    ERROR at line 15:
    ORA-01799: a column may not be outer-joined to a subqueryHow to resolve this issue?
    Regards.

    And any luck with this?
    SQL> with emp as
      2  (select 100 empno, 'Abcd' ename, 1000 sal, 10 deptno from dual
      3  union all
      4  select 101 empno, 'RRR' ename, 2000 sal, 20 deptno from dual
      5  union all
      6  select 102 empno, 'KKK' ename, 3000 sal, 30 deptno from dual
      7  union all
      8  select 103 empno, 'PPP' ename, 4000 sal, 10 deptno from dual
      9  )
    10  ,dept as
    11  (select 10 deptno, 'FINANCE' dname from dual
    12  union all
    13  select 20 deptno, 'SALES' dname from dual
    14  union all
    15  select 30 deptno, 'IT' dname from dual
    16  union all
    17  select 40 deptno, 'HR' dname from dual
    18  )
    19  select e.empno, e.ename, e.sal, d.deptno, d.dname
    20  from emp e,
    21       (select decode(a.deptno, 10, b.deptno, a.deptno) deptno, decode(a.deptno, 10, b.dname, a.dname) dname
    22      from dept a, (select deptno, dname
    23                    from dept
    24                      where dname = 'SALES'
    25                     ) b
    26       ) d
    27  where e.deptno(+) = d.deptno
    28  /
         EMPNO ENAM        SAL     DEPTNO DNAME
           101 RRR        2000         20 SALES
           101 RRR        2000         20 SALES
           102 KKK        3000         30 IT
                                       40 HR
    SQL> Cheers
    Sarma.

  • How do i delete a contacts sub folder from my iphone?

    How do i delete a contacts sub folder from my iPhone?

    Hi, sure.
    Under "contacts" "Groups" I have the "All Contacts" option at the top, underneath that i have 3 empty subfolders that have come in from my PC Outlook program. I've deleted these from Outlook, shut Outlook down, shut iTunes down, re started both programs and re synced my iPhone4 and iPhone5. They are still on the iPhone 4, just given to my wife, but have disappeared from my iPhone 5!

  • How to pass runtime parameters to Oracle Query from xMII server

    Please can anybody  help me that how to pass runtime parameter to Orcle Query  from xMII server.

    It works the same way as I described in this thread [How to pass runtime parameters to MySQL Query from xMII server].  It does not matter the datasource MII will work the same for all queries, at least for passing in parameters.  How to write those queries and their datatypes will be the differences.

  • How to pass runtime parameters to MySQL Query from xMII server

    Please can anybody help in How to pass runtime parameters to Orcle Query from xMII server

    The answer is the same as for your other thread.  The mechanism is the same regardless of the end database.  The SQL  syntax will be different for each database vendor depending upon which functions you are invoking.  The main areas of difference between SQL Server, Oracle, DB2, etc. deal with dates (times also) and strings, but there are others as well.
    Regards,
    Mike

  • How to find the number of fetched lines from select statement

    Hi Experts,
    Can you tell me how to find the number of fetched lines from select statements..
    and one more thing is can you tell me how to check the written select statement or written statement is correct or not????
    Thanks in advance
    santosh

    Hi,
    Look for the system field SY_TABIX. That will contain the number of records which have been put into an internal table through a select statement.
    For ex:
    data: itab type mara occurs 0 with header line.
    Select * from mara into table itab.
    Write: Sy-tabix.
    This will give you the number of entries that has been selected.
    I am not sure what you mean by the second question. If you can let me know what you need then we might have a solution.
    Hope this helps,
    Sudhi
    Message was edited by:
            Sudhindra Chandrashekar

  • TS1424 apple store,just wanted to check on how to change my area settings in itunes from United States to United Arab Emirates(that's where i stay).it got changed when i tried to download google maps from the US store in itunes.please help me out here.Tha

    Apple store,just wanted to check on how to change my area settings in itunes from United States to United Arab Emirates(that's where i stay).it got changed when i tried to download google maps from the US store in itunes.please help me out here.Thanks

    Please please help me, if you know how.

  • How to avoid duplicates in CROSS JOIN Query

    Hi,
    I am using CROSS JOIN to get all the subset of a table col values as shown below:
    PRODUCT (Col Header)
    Bag
    Plate
    Biscuit
    While doing cross join we will get as
    Bag Bag
    Bag Plate
    Bag Biscuit
    Plate Bag
    Plate Plate
    Plate Biscuit ..... like this
    By placing where condition prod1 <> prod2 to avoid Bag Bag and Plate Plate values. So the output will be like below
    Bag Plate
    Bag Biscuit
    Plate Bag
    Plate Biscuit
    Now "Bag Plate" and "Plage Bag" are same combination how to avoid these records. My expected result is
    Bag Biscuit
    Plate Biscuit
    How to derive this ?
    Sridhar

    Hi,
    This is the the solution that I found as fit to the OP question, but
    Visakh16 already posted the same idea (assuming the names are unique) from the start and I don't think that anyone notice it!
    Sridhar.DPM did
    you check Visakh16's response
    (the second response received)?!?
    I will mark his response as an answer. If this is not what you need pls clarify and you can unmark it :-)
    [Personal Site] [Blog] [Facebook]

  • Urgent - Cannot run sub query from VB 6

    Hello!
    I'm having a problem with my Oracle OLE DB connection in windows using Visual Basic 6.0 SP3.
    I can run normal queries just fine, but a correlated sub query like this:
    select A.col_a, (select col_b from Tab_B where id = A.id) from Tab_A A
    returns the following error:
    "ORA-00907: missing right parenthesis"
    But I'm able to run the query witout errors in Toad with the correct result!
    So basically, I cannot run a (correlated?) sub query via OLE DB...
    What am I doing wrong?? Is it a parameter that I need to set on the connection of command?
    I'm not using stored procedures, only plain text SQL.
    Very thankful for a quick answer, this is really urgent. If you have the possibility, please e-mail me at:
    [email protected]
    Thank you in advance.
    Best regards,
    Bnar Baban

    Hi!
    I'm running the latest version of Oracle OLE DB...when checking more in detail, it seems that the provider parses the code in a way, that makes the "(select" part of the sub statement be interpreted as a column name....when it does not find a right parenthesis, but a white space, it complains.
    I switched to Microsoft MSDAORA provider, and now it works perfectly...
    /Bnar

  • Show query from prepared statement

    Hi all!
    Does someone knows how to get the whole generated query from a prepared statement?
    I want to know if the parameters are set correctly and therefore want to print it out to screen
    before the query is executed.
    Thanks in advance.

    You can't. At least not using standard JDBC. This is partially because the driver doesn't necessarily generate a query from the prepared statement, it can make a remote procedure call instead, for example.
    Alin.

  • How to Create WebService (the Server, not Client) from existing WSDL

    Does anyone have any suggestions on how to create a WebService from existing WSDL.  I have been asked to implement a WebService (the Server) based on WSDL from a standards based consortium.  I have created several WebServices in the past and the generated WSDL under my control.  Does Axis WebServices generate WebService service stub Java code?

    Hai
      you can create stubs for AXis webservices also
      for help use the following link
    http://www.onjava.com/pub/a/onjava/2002/06/05/axis.html?page1

  • How do I download my music and photos from existing iPad to new iphone

    How do I download music and photos from existing iPad to new iphone

    Perform a backup to iTunes from the old device and then a restore to the new device, use ITunes to do this.  BTW, always sync photos to a computer to store them safely (use iPhoto on a mac or to a designated folder on a PC).  Never trust an iOS device to keep photos without having them synced to a computer.

  • How to do an INNER JOIN sub-query?

    Can't seem to find anything that would help me out with this.
    My prototype query goes like this but its giving me a ORA-00905: missing keyword
    SELECT Poker_Site.site_name, bonus.sign_up_bonus
         FROM poker_site
         INNER JOIN bonus
         WHERE Poker_site.site_name = 'Poker Stars'
         ON Poker_Site.site_name = bonus.site_name;

    INNER JOIN join must be immediately followed by ON and only then by WHERE:
    SELECT Poker_Site.site_name, bonus.sign_up_bonus
    FROM poker_site
    INNER JOIN bonus
    ON Poker_Site.site_name = bonus.site_name
    WHERE Poker_site.site_name = 'Poker Stars';SY.

  • How to avoid @ for running a sql query in sqlplus

    Hi friends,
    Is there a way to avoid typing @ for the execution of every sql script in the database. Maybe playing around with the login.sql or something.
    I am bored of typing shift+@ every execution of running any of my scripts(i have nearly 3000 scripts) :(. May sound like a request from a lazy guy , but still can anyone please suggest some solution.??
    like instead of
    14:12:04 sa@TESTDB> @active
                                                                     Client                                                 last
       SID   SER# LOGON_AT        USERNAME   OSUSER     MACHINE      PID      MODULE               PROGRAM    SQL_ID        call et
       225      1 17-jun 07:00               oracle     tkxti019      4543                          oracle@tkxt                 55h 11m 43s
       224      1 17-jun 07:00               oracle     tkxti019      4651                          oracle@tkxt                 55h 11m 43s
       223      1 17-jun 07:00               oracle     tkxti019      4708                          oracle@tkxt                 55h 11m 43ssomething like below is needed
    14:12:05 sa@TESTDB> active
                                                                        Client                                                 last
       SID   SER# LOGON_AT        USERNAME   OSUSER     MACHINE      PID      MODULE               PROGRAM    SQL_ID        call et
       225      1 17-jun 07:00               oracle     tkxti019      4543                          oracle@tkxt                 55h 11m 43s
       224      1 17-jun 07:00               oracle     tkxti019      4651                          oracle@tkxt                 55h 11m 43s
       223      1 17-jun 07:00               oracle     tkxti019      4708                          oracle@tkxt                 55h 11m 43sThanks,
    Kunwar

    Kunwar wrote:
    I am bored of typing shift+@ every execution of running any of my scripts(i have nearly 3000 scripts)If you're running several scripts in one go, why not put them into a script, so that you only have to call that script and the rest will run automatically?
    eg:
    main.sql:
    Prompt Running script1
    @script1
    Prompt Running script2
    @script2
    Prompt Running script3000
    @script3000
    SQL> @main
    Running script1
    Running script2
    Running script3000
    ...

  • How do I get all my sub-folders from Yahoo to show up in Mozilla

    I installed Mozilla Thunderbird on my Home PC and Office Laptop. On my PC all my sub-folders were imported automatically. On my Laptop Thunderbird is not showing all the sub-folders I use in Yahoo to keep my emails organized. This is not the local folders that I can set up in Thunderbird. It's the folders I have created in Yahoo for years.

    Pop mail accounts can only connect to server, check Inbox for new messages and download from the server Inbox to the mail account Inbox in Thunderbird. This is how all pop mail accounts work.
    You can get other emails in other folders downloaded by logging on to webmail and moving the emails back into the Inbox and then click GetMail.
    Suggest you do this one folder at a time.
    Imap mail accounts see a remote view of the server folders. You subscribe to see folders. You can also choose to synchronize folders.
    If you want to see various server folders then you have to use IMAP.
    You cannot change a pop into an imap, there are many differences.
    Create a new exisiting mail account and make sure it is an IMAP setting before you click on 'Done'. Use 'Manual config' button if necessary to change settings.

Maybe you are looking for

  • ITunes WILL NOT WORK AT ALL

    I have a Toshiba M400 Tablet Laptop running Windows XP Tablet. I have a Motion Computing M1400 tablet. Itunes works on the M1400. The Toshiba is Brand New!!! Fully decked out. iTunes will install but crashes on startup of the app. I have followed sev

  • Disk utility app no longer working

    I just discovered my disk utility app is no longer working.  When I launch the app, its window opens and the message "Gathering disk information" along with the spinning gear icon appears in the window. Then the gear just spins and spins and ....  I

  • What are the assessment options in Captivate 8 for the following scenario:

    I have one Captivate  project with five modules, after each module I want to have mandatory questions (user need to answer to proceed and pass the course) and optional questions (user can skip, not included in the final score). I am using Oracle LMS.

  • Now a simple question of Field exit.

    well, im really very glad because my last post was a success and i can solve de problem!!!!thank you all... this time i need in the VF01 on one field ('Reference'/Xblnr), when the user press save, to show some popup allowing entry data, so the user m

  • Sum hidden fields in web dynpro ALV reports

    Hi everyone Could anyone tell if it is possible to sum a field that is hidden in an ALV Report in Web Dynpro? I need to hide a row so as not to be seen by the user (like the filter option) but with the need that the value that is stated in that hidde