T-SQL - Using Column Name in where condition without any references when having multiple tables that are engaged using multiple joins.

Hi All,
I am a newbie for T-Sql, I came across a SP where multiple tables are engaged using multiple joins but the where clause contain  a column field without any table reference  and assigned  for an incoming variable,like 
where 'UserId = @UserId'
instead -  no table reference like 'a.UserId = @Userid'   ............ Can any please do refer to me any material that clears my mind regarding such issue................... help is appreciated.
Thank You.

As suggested above, use table alias with columns for unique referencing and to make the code easier to read.
BOL example for table aliasing:
USE AdventureWorks;
GO
SELECT S.CustomerID, S.Name AS Store, A.City, SP.Name AS State, CR.Name
AS CountryRegion
FROM Sales.Store AS S
JOIN Sales.CustomerAddress AS CA ON CA.CustomerID = S.CustomerID
JOIN Person.Address AS A ON A.AddressID = CA.AddressID
JOIN Person.StateProvince SP ON
SP.StateProvinceID = A.StateProvinceID
JOIN Person.CountryRegion CR ON
CR.CountryRegionCode = SP.CountryRegionCode
ORDER BY S.CustomerID ;
GO
GO
LINK:
http://technet.microsoft.com/en-us/library/ms124824(v=sql.100).aspx
Check the use of TABLE ALIASes and COLUMN ALIASes in the following blog:
http://www.sqlusa.com/bestpractices2005/organizationtree/
Without the use of aliases the code would become unreadable.
Kalman Toth Database & OLAP Architect
Free T-SQL Scripts
New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

Similar Messages

  • How to use MONTH NAME in where condition in date column?

    Hi dudes,
    this is the table.
    sql>desc ACMINUTESPDFTEST;
    Name Null? Type
    ACDATE DATE
    TYPES VARCHAR2(10)
    here i have tried the following 2 queries,but i could not get the correct result
    select types,seqno,acdate from ACMINUTESPDFTEST where acdate like to_date('NOV','MON');
    or
    select types,seqno,acdate from ACMINUTESPDFTEST where acdate = to_date('NOV','MON');
    (for both the query the output is same)
    TYPES ACDATE
    PINK 01-NOV-10
    but the table having following data:
    TYPES ACDATE
    PINK 14-NOV-10
    WHITE 15-NOV-10
    PINK 01-NOV-10
    Any suggestion why i could not get correct result.

    bharathit wrote:
    Thanks for toon and divya...it solved my problem and my question how will you select between two months..
    select types,acdate from ACMINUTESPDFTEST where to_char(acdate,'MON') >= 'SEP' AND to_char(acdate,'MON') <= 'OCT';
    and i got
    no rows selected
    Edited by: bharathit on Nov 2, 2010 10:37 PMIf you're interested in finding dates in a range of months regardless of the year then try this:
    select ...
    from   ...
    where  to_number(to_char(date_column,'MM')) Between 9 And 10;You could also do something like:
    select ...
    from   ...
    where  to_number(to_char(date_column,'MM')) In (1,4,7,10);If you are interested in dates in a range of months in a particular year however, use something like this:
    select ...
    from   ...
    where  date_column >= date '2010-09-01' and
           date_column < date '2010-11-01' and

  • Passing the column name on Where condition based on input parameter

    Hi,
    I am using Oracle10g. Following are my table schema.
    Table Name : Codes
    Columns( ID, Level0, Level1,Level2)
    View Name : SampleView
    I have a scenario : A parameter will be passed to my view from C# application. I need to cut the last 4 places of the parameter and need to check 4 conditions as follows :
    1. IF last 4 places of parameter contains the value as "AMPD" then pass level0 column on where condition.
    Sample code : A123XPAMPD
    Expeted Result: Select * from Codes where Level0 ='A123XPAMPD'
    2. IF last 4 places of parameter contains the value as "Alpha numeric" then pass level1 column on where condition.
    Sample code : A123XPAA00
    Expeted Result: Select * from Codes where Level1 ='A123XPAA00'
    3. IF last 4 places of parameter contains the value as 0000 then pass level1 column on where condition.
    Sample code : A123XP0000
    Expeted Result: Select * from Codes where Level1 ='A123XP0000'
    4. IF last 4 places of parameter contains the value as (cannot be all 0's) and cannot contain "Alphabets" then pass level2 column on where condition.
    Sample code : A123XP1001
    Expeted Result: Select * from Codes where Level2 ='A123XP1001'
    Could any one please help me on writing this logic inside the view.
    Thanks in advance.

    Do you want to make sure that at least one alphabet and one number is there?
    select case
         when regexp_like('1111','^[a-zA-Z]+$') -"This says - Only alphabets, not even space
              THEN 'Alphabets'
         when regexp_like('1111','^[a-zA-Z0-9]*$') --"This says - Only alpha-numeric, not even space
          and regexp_like('1111','[a-zA-Z]') --"To make sure atleast one alphabet is there
          and regexp_like('1111','[0-9]') --"To make sure atleast one number is there
              THEN 'AlphaNumeric'
           else 'NULL' --"This is a string. Not actual NULL
          end
    from dual;
    {code}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • How to Concatenate Table name and Where condition at runtime

    I am passing parameter as User and Zone to Stored Procedure.How to concatenate Table Name
    and WHERE CONDITION in SQL Statement.i have different type of users and zones.

    Hi !
    declare
      cur sys_refcursor;
      r emp%rowtype;
      v_sql varchar2(512);
    begin
    -- do your logic here
      v_sql := 'select * from emp';
      open cur for v_sql;
      loop
        fetch cur into r;
        exit when cur%notfound;
        dbms_output.put_line(r.ename);
      end loop;
      close cur;
    end;In this example you can see how can be done this with cursor vars .. You should concatenate v_sql string according to your requirements.
    But as in further posts has already been mentioned , be carefull at publishing such kind of procedures and think on security.
    Also when you want dynamicaly change from clause , you should consider using different records to accept data ? Maybe all your tables has the same structure and then this problem will be smaller.
    T
    T

  • Can we use Column Names in Parameter Cursor

    Hi
    can we use Column Names in Parameter Cursor??
    DECLARE
    CURSOR Emp_Cur (P_Deptno NUMBER)
    IS
    SELECT Empno, Ename
    FROM Emp
    WHERE Deptno = P_Deptno;
    BEGIN
    FOR Emp IN Emp_Cur(10)
    LOOP
    DBMS_OUTPUT.PUT_LINE('The Employee Number is: '||emp.Empno);
    DBMS_OUTPUT.PUT_LINE('The Employee Name is: '||emp.Ename);
    END LOOP;
    FOR Emp IN Emp_Cur(20)
    LOOP
    DBMS_OUTPUT.PUT_LINE('The Employee Number is: '||emp.Empno);
    DBMS_OUTPUT.PUT_LINE('The Employee Name is: '||emp.Ename);
    END LOOP;
    END;
    In the above Program, I send Deptnumber. If i send Column names like Empno, Ename. What can i do??
    If Declare Samething Through Parameter Cursor, it doesn't accept VARCHAR2(Size)

    For parameters you don't use size, just the type (DATE, NUMBER, VARCHAR2, CLOB, ...)
    DECLARE
      CURSOR Emp_Cur (P_Ename VARCHAR2)
      IS
        SELECT Empno, Ename
        FROM Emp
        WHERE Ename = P_Ename;
    BEGIN
      FOR Emp IN Emp_Cur('SCOTT')
      LOOP
        DBMS_OUTPUT.PUT_LINE('The Employee Number is: '||emp.Empno);
        DBMS_OUTPUT.PUT_LINE('The Employee Name is: '||emp.Ename);
      END LOOP;
    END;

  • [[DataDirect][ODBC SQL Server Wire Protocol driver][Microsoft SQL Server]Column name or number of supplied values does not match table definition.]

    Hii ..
    need help on this ..
    This what I am doing ..
    I am using a DATAEXPORT function to export level0 data from my essbase 11.1.2.2 to Microsoft SQL 2008 tables.
    So what I did first I exported the level0 data to a flat file using DATAEXPORT and the created the SQL columns by the same  in that order only in my SQL table.
    When I run it fails with this error:
    ODBC Layer Error: [21S01] ==> [[DataDirect][ODBC SQL Server Wire Protocol driver][Microsoft SQL Server]Column name or number of supplied values does not match table definition.]
    [Tue Jul 23 18:26:07 2013]Local/dataexp/dataexp/admin@Native Directory/1209813312/Info(1021014)
    ODBC Layer Error: Native Error code [213]
    [Tue Jul 23 18:26:07 2013]Local/dataexp/dataexp/admin@Native Directory/1209813312/Error(1012085)
    Unable to export data to SQL table [dataexp]. Check the Essbase server log and the system console to determine the cause of the problem.
    [Tue Jul 23 18:26:07 2013]Local/dataexp/dataexp/admin@Native Directory/1209813312/Info(1021002)
    SQL Connection is Freed
    [Tue Jul 23 18:26:07 2013]Local/dataexp/dataexp/admin@Native Directory/1209813312/Warning(1080014)
    Transaction [ 0x1c50001( 0x51ee7d66.0x80342 ) ] aborted due to status [1012085].
    [Tue Jul 23 18:26:07 2013]Local/dataexp/dataexp/admin@Native Directory/1209813312/Info(1012579)
    Total Calc Elapsed Time for [test.csc] : [1.44] seconds
    =============================================================
    I did a simple test on my Sample.basic application then ..
    loaded the calc data to it and then used the below script to export to a flat file
    //ESS_LOCALE English_UnitedStates.Latin1@Binary
    SET DATAEXPORTOPTIONS
                    DataExportLevel "Level0";
                    DataExportOverwriteFile ON;
                    DataExportColFormat OFF;
                    DataExportDimHeader OFF;
    FIX(
                "Jan",
                "Sales",
                "Actual"
    /*DATAEXPORT "File" "," "/home/hypadmin/samtest.txt";*/
    DATAEXPORT "DSN" "Abhitest" "sample" "sa" "welcome1";
    ENDFIX
    out put as below:
    "Sales"
    "100-30","California"
    "Jan","Actual",145
    Now In sql I created only 3 columns with name Jan/Sales/Actual and when I run this script again with comments removed .. I get the same error as what I have got in my first test case with other application ..
    but when I create the columns with same name as what its in export
    Sales/100-30/Califirnia/Jan/Actual
    It created the new rows successfully ..
    So with this I think the error which I am getting with my other application might be because of the same column issue  .. but then I have created all the columns by looking at the export file only as I did in sample ..
    Any idea would be helpful ..
    Thanks
    Abhishek
    I

    First make sure you add
    DataExportRelationalFile ON;
    to your set commands it is missing
    I alwats like to also add
    DataExportColHeader dimensionName;
    so I am sure what dimension is getting put into the columns.
    Then count the number of dimensions in your outline (exclude attribute dimensions). You need at least that many columns in your table  -1 + the number of  members you will be returning as columns in the export
    Taking your example Sample basic has 5 dimensions
    Measures
    Years
    Scenario
    Product
    Market
    Since you did not specify a dataexportcolheader it took the dense dimension Scenario as the columns. Your fix statement is limiting that to one member. Doing the math
    5 -1 + 1 = 5 columns in your table which is what you found works.  Suppose you fixed on bothe Actual and budget in scenario then you would need 6 columns 5 -1 +2

  • How do I get files from multiple DVDs that are using thesame file names?

    How do I get files from multiple DVDs that are using thesame file names? Message says "file already exists in catalog"
    Message was edited by: marcr56

    marcr56
    I am viewing your question from different perspective, that is, the issue that you face when you are ripping VOBs from a second DVD-VIDEO on DVD disc using Premiere Elements,
    It is best to give the Premiere Elements version and computer operating system that it is running on. In the absence of that, I will generalize.
    Assuming that you are using
    Premiere Elements 12
    Add Media
    "DVD Camera or Computer Drive"
    Video Importer
    Typically the Video Importer Save In: is C:\Users\Owner\Videos
    Each of your DVD discs is going to have the same names for the ripped VOBs (VTS_01_1.VOB and so on depending on the duration of the movie). Consequently, after the ripping of the first DVD's VOBs and their save to Videos, you will end up with that "files already existing..." block for the ripping of the VOBs from the second DVD.
    The answer is, for each DVD disc VOB ripping, to plan ahead and create and set for different folders in Videos in the Save In field of the Video Importer.
    Please review and then let us know if that works for you. Please do not hesitate to ask if you need clarification on anything that I have written.
    Thank you.
    ATR.

  • Where are stats that are gathered using dbms_stats stored?

    where are stats that are gathered using dbms_stats stored?

    http://docs.oracle.com/cd/E11882_01/server.112/e16638/stats.htm#PFGRF94765

  • Hello, i lost my iphone5 32gb and i want to track it but the thing is that in my iphone5 i did not setup the find my iphone application :'( ...so, is there any option where i can track my phone or block it that nobody can use it..please help me out

    Hello, i lost my iphone5 32gb and i want to track it but the thing is that in my iphone5 i did not setup the find my iphone application :'( ...so, is there any option where i can track my phone or block it that nobody can use it..please help me out

    Unfortunately if you did not set up 'Find My iPhone', there is no way to remotely track or wipe the device.

  • Find out particular printers that are being used by background jobs.

    Find out particular printers that are being used by background jobs..
    Hi Gurus,
    I have to remove some printers from SPAD, but before removing those printers I have to make sure that those are not being used by any background jobs.   The table TBTCP can be used to identify which jobs are still using those printers, but this is a tedious process. 
    Any input would be highly appreciated.
    Thank you
    Adil

    Hi Adil,
    I'm lazy so I'd just run this SQL
    select distinct(jobname), pdest from SAPSR3.TBTCP where PDEST in ('LP01', 'LOCL') ;
    Just put the printers you want as shown above and just perform a little manual cross check by checking the job in SM37.
    And that's it .....
    Cheers,
    Amerjit

  • My requirement is to update 3 valuesets daily based on data coming to my staging table. What is the API used for this and how to map any API to our staging table? I am totally new to oracle and apps. Please help. Thanks!

    My requirement is to update 3 valuesets daily based on data coming to my staging table. What is the API used for this and how to map any API to our staging table? I am totally new to oracle and apps. Please help. Thanks!

    Hi,
    You could use FND_FLEX_LOADER_APIS.UP_VALUE_SET_VALUE to upload them from staging table (I suppose you mean value set values...).
    You can find a sample scripts if you google around.
    What do you mean "how to map any API to our staging table" ?
    You should do at least the following mapping (which column(s) in the staging table will provide these information):
    - the 3 value sets name which you're going to update/upload (I suppose these are existing value sets or which have been already created)
    - the value set values and  description
    Try to start with something and if there is any issues the community could then help... but for the time being with the description of the problem you have provided, that's the best I can do...

  • EM monitor indexes that are being used?

    Hello,
    I wonder if with Oracle Enterprise Manager dbconsole, is possible monitor the indexes that are being used during a determine period as in TOAD?
    Thanks

    Hi,
    Index monitoring is started and stopped using the ALTER INDEX syntax shown below.
    ALTER INDEX my_index_i MONITORING USAGE;
    ALTER INDEX my_index_i NOMONITORING USAGE;
    Information about the index usage can be displayed using the $OBJECT_USAGE view.
    Query :-
    SELECT index_name,
    table_name,
    monitoring,
    used,
    start_monitoring,
    end_monitoring
    FROM v$object_usage
    WHERE index_name = 'MY_INDEX_I'
    ORDER BY index_name;
    The V$OBJECT_USAGE view does not contain an OWNER column so you must to log on as the object owner to see the usage data
    Thanks
    Pavan Kumar N.

  • Where can I find the equivalent tools in Photoshop that are in the develop module of Lightroom

    Friends:
    Where can I find the equivalent tools in Photoshop that are in the develop module of Lightroom?  For example I would like to use the shadow, clarity, lens correction and such tools but cannot find them in Photoshop.
    Thanks amigos
    Migs

    The obvious or not so obvious first. Depending on your knowledge. When you open a tiff, jpg, or camera' raw format they can be opened in Adobe Camera raw first which has identicle controls to lightroom's develop module.
    Starting with I beleive CS5 maybe 4, some of the tools made their way into photoshop it self. Take a look at the camera lens filter, the Image>Adjustment menu or the adjustment layers which now support vibrance for example.

  • Find out which charateristics that are in use

    Hi
    We use classes linked to our document types.
    And the classes has a lot of characteristics.
    Is there an easy way to find out which characteristics that are in use (documentens where values are given), and on how many documents they have been used on?
    Best regards
    Tom Saga

    See if table AUSP serves your purpose.
    Regards,
    Pradeepkumar Haragoldavar

  • IPod contains files that are in use by another application

    If you have ever received a message from iTunes saying that, "iTunes cannot update iPod because it contains files that are in use by another application," then take a look at this thread because I have had many problems with this and discovered a solution that most likely will work. Ok, lets begin:
    1. Updating/Restoring does not work. If you have this problem and get the above message continue reading.
    2. Plug your iPod into your USB port. Allow iTunes to load and recognize the iPod. It shall update itself automatically.
    3. When iTunes is finished, go to the "Start Menu."
    4. Open "My Computer"
    5. On the main screen, scroll to "Devices with Removable Storage." Click on your iPod.
    6. After clicking on the iPod, go to the left-side bar and under "System Tasks," click "Eject this disk."
    7. Once this is done, return to iTunes and click "Update."
    8. It should come up with a message saying something like, "Updating (Name of iPod) iPod."
    Congratulations, you have just solved your problem! Good luck enjoying the wonderful updates that iTunes has to offer.
    Darth Bob
    P.S. Let me know if there is anything I can imporve on, I'm sort of new to this, but love messing with the computer. Thank You!
    Dell Demension 8400   Windows XP   4GB iPod Nano Second Generation Blue

    I am experiencing the same message when I try and sync either my or my wife's iPod on my Mac. I simply acknowledge it and everything seems to work fine but I wonder what's going on. I used to have problems dismounting my iPod but that seems to have gone away with iTunes 7.
    Any thoughts for us Mac guys?
    G5 tower 1.8 single proc   Mac OS X (10.4.8)   Purchased in December 2003

Maybe you are looking for

  • Remote update of a 1000 series LWAP

    My company recently went from an old airspace 4024 with firmware 3-2-195-13 to a new 4402-50 running 4-1-185-0. Using Option 43 in DHCP allowed the new 4402 to see the AP's on different VLan's and Subnet's and issue IP addresses to the AP's and clien

  • Edit the payment total in text field on PLD

    Hello Everybody, Does anybody know any way to edit the text which appears on document layouts and says the payment total amount in text format? This is system variable (125) originally, but we want to re-edit this text. Is there any way for that? Tha

  • Am I on the right track? Instead of parallel arrays I am doing this...

    Hi. I am making a phonebook aplication and am not allowed to use a database as yet for the application(will be converted into a database application at a later point.) The code is not complete and I am aware that thereating are many things missing. I

  • Epson R2400 (and maybe other Epson Printers) and Snow Leopard:  A Solution

    I installed Snow Leopard over the weekend and everything seemed to go fine, except the re-installation of my Epson R2400.  It didn't work.  The Epson Web site provides Snow Leopard assistance for the R2400, but it is counter-intuitive.  The following

  • Errors creating recovery disk

    I have received error 020150-20-00000000 twice when attempting to create the recovery disks.  It has happened on the first disk with two different files when trying to verify.. I have a Satelite L505D-LS5010 with win 7 Thanks Frank