IF EXISTS Logic

  • Hi Team,

    I am having a temp Table "@Temp_Table" and a physical Table "St_Value"

    @Temp_Table Contains

    Case1:

    Column_Name|Value

    ------------------------------

    Col1123

    Col2NULL

    "St_value" Contains

    Column_Name|Value

    -------------------------------

    Col1123

    Col2582

    Col3

    My Query is :

    if @temp_table contains Col1 and its value then

    select "col1 : 123"

    for record col2 there is no value (NULL) then

    only the column lable should be include.

    select "Col1 :123,

    Col2 :"

    then for remaining records it should check in "St_value" table

    Final string should be

    select "Col1 :123,

    Col2 :

    Col3 :456"

    Exact Requirement :If temp table contains label "column_name" and its "value" then only Column_Name : Value should be included

    else only column_name should be included, for remaining records it should check in physical table.

    am using below logic, but its not working.

    Please help..

    SELECT @query1 =

    IF EXISTS (SELECT col1 from @Temp_Table)THEN

    'Col1: ' +rtrim(Col1) + ' (Value ' + rtrim(convert(varchar, Value,107)) + ')' +CHAR(10)

    ELSE

    'Col1: ' ' Value : '

    ELSE

    CASE WHEN Col1 IS NULL or Col1 = '' THEN ''

    ELSE CASE WHEN Value IS null then

    'Col1: ' + rtrim(Col1) +CHAR(10)

    ELSE 'Col1: ' +rtrim(Col1) + ' (Expires ' + rtrim(convert(varchar, Value,107)) + ')' +CHAR(10)

    END

    END+

    from St_Value

    Please Help...?

  • Why are you trying to use dynamic sql. It's look like you need full outer join:

    SELECT ISNULL(t.Column_Name, v.Column_Name) AS Column_Name

    ,CASE WHEN t.Column_Name IS NULL THEN v.Value

    ELSE t.Value

    END AS Value

    FROM @Temp_Table t

    FULL OUTER JOIN St_Value v

    ON v.Column_Name= t.Column_Name

    _____________________________________________
    "The only true wisdom is in knowing you know nothing"
    "O skol'ko nam otkrytiy chudnyh prevnosit microsofta duh!":-D
    (So many miracle inventions provided by MS to us...)

    How to post your question to get the best and quick help[/url]

Viewing 2 posts - 1 through 1 (of 1 total)

You must be logged in to reply to this topic. Login to reply