In where condition use column value which contains column name

  • Hi Team,

    Greetings!

    I have below table. let table name =Emp

    Capture

    I need to query in the table like below.

    select * from Emp

    where (Here instead of writing country='India', I want to use the column business_rule directly so that i can get the records )

    Thanks in advance!

  • You'll be needing to use dynamic SQL to make that happen.

    But if all of your business rules are like that, why not just join on (Name, Country)?

    The absence of evidence is not evidence of absence
    - Martin Rees
    The absence of consumable DDL, sample data and desired results is, however, evidence of the absence of my response
    - Phil Parkin

  • Business rule column in not a consistent one. I have given two columns as example. But it may contain 2, 3 or more column names under business_rule.

    Yes, I tried with dynamic sql but could not make it. So if any suggestion how to build the query

    Thanks

    Rohit

  • Note that the following is vulnerable to SQL Injection. If your business rules table is at any risk of being compromised, don't use this code.

    DROP TABLE IF EXISTS #Rule;

    CREATE TABLE #Rule
    (
    Name VARCHAR(50) NOT NULL
    ,Country VARCHAR(100) NOT NULL
    ,BusinessRule VARCHAR(1000) NOT NULL
    );

    INSERT #Rule
    (
    Name
    ,Country
    ,BusinessRule
    )
    VALUES
    ('RK', 'India', 'Name = ''RK'' and Country = ''India''');

    SELECT *
    FROM #Rule r;

    DECLARE @SQL VARCHAR(8000) = 'SELECT * FROM EMP WHERE ' +
    (
    SELECT TOP (1) r.BusinessRule FROM #Rule r WHERE r.Country = 'India'
    );

    SELECT @SQL;

    --EXEC (@SQL)

    The absence of evidence is not evidence of absence
    - Martin Rees
    The absence of consumable DDL, sample data and desired results is, however, evidence of the absence of my response
    - Phil Parkin

  • In a SELECT, there is no late binding of columns. You have to use dynamic SQL, as Phil noted, but there are all sorts of security problems here. You are risking your system here by trying to store business rules like this.

  • rohit.kumar.barik wrote:

    Business rule column in not a consistent one. I have given two columns as example. But it may contain 2, 3 or more column names under business_rule.

    Yes, I tried with dynamic sql but could not make it. So if any suggestion how to build the query

    Thanks

    Rohit

    Please post the dynamic SQL you tried using as well as the issue(s) you experienced.

     

Viewing 6 posts - 1 through 5 (of 5 total)

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