Dynamically adding filters in where clause in sql server

Hello I have a question, 
may be asked many times but could not find a thread,
I have 8 parameters,... and user can select any of these parameters they can select 3,4 or all 8.
I know we could use dynamic sql for this, because the sql is same.. just the where clause changes as how many parameters we are selecting, 
i am using sql server 2012.. is there a easy way to manage this,
Please let me know.

Consider static (dynamic) search:
http://www.sommarskog.se/dyn-search.html
Alternative, dynamic SQL:
http://www.sqlusa.com/bestpractices/dynamicsql/
Kalman Toth Database & OLAP Architect
SQL Server 2014 Database Design
New Book / Kindle: Beginner Database Design & SQL Programming Using Microsoft SQL Server 2014

Similar Messages

  • Include dynamic conditions in the where clause

    Hi All,
    I have an requirement where i need to dynamically include the conditions in the where clause based on the bind variable.
    My condition is like this.
    SELECT f.scheduled_date, a.bld_id, a.room_id, a.cage_id, f.test_num
    FROM feeding_test_results f,
    v_onl_gf_anmls a
    WHERE f.sak_feeding_test_res > 5000000
    AND f.anml_id(+) = a.anml_id
    AND f.bld_id = 'A5'
    AND f.room_id > 0
    AND f.cage_id > '0'
    case when :check_value = 1 Then
    AND scheduled_date <= '16-Apr-2009'
    AND scheduled_date >= '06-Apr-2009'
    Else
    AND scheduled_date = '16-Apr-2009'
    End
    AND f.feeding_status <> 'X') f
    Kindly anyone help me how to acheive this.
    Thanks & Regards,
    P. Gayathri Devi

    michaels2 wrote:
    and scheduled_date <= case when :check_value = 1 then date '2009-04-16' end
    and scheduled_date >= case when :check_value = 1 then date '2009-04-06' end
    and scheduled_date = case when not :check_value = 1 then date '2009-04-16' end
    Hmmm, you may want some NVL's around those case statements such as..
           and scheduled_date <= NVL(case when :check_value = 1 then date '2009-04-16' end,scheduled_date)
           and scheduled_date >= NVL(case when :check_value = 1 then date '2009-04-06' end,scheduled_date)
           and scheduled_date = NVL(case when not :check_value = 1 then date '2009-04-16' end,,scheduled_date)or some such thing. Otherwise the comparisons with Null will just cause it all to fail.

  • Row Level Security using BO SDK - Dynamic Group and Criteria (where clauses)

    To the Universe Gurus out there:
    I have a rather daunting task of implementing a Row Level Security on a number of tables within our project using BO XI R2 SP2 with SQLServer 2005. Given the nature of the requirements around this (listed below), I am going to go with BO SDK to accomplish the creation of Restrictions. That said, I need some insight into some of the problem areas I have listed below. Any help is much appreciated.
    Background:
    We have 11 tables that are to be restricted.
    Each table is accessible to potentially 1..* group of users only.
    For eg SALES is accessible to ALL_SALES members only.
    Each row within each table is accessible to 1..* groups of users only. The restriction will occur on 2 columns Jurisdiction and LineID on SALES table.
    For eg
    1)Rows with NY Jurisdiction and LineID=123 are accessible to NY_SALES_ADMIN group only initially.
    2)NY_ADMIN will then approve that the above rows be open to NY_SALES_INTERNAL group only. This approval in turn will call upon the BO SDK to add a new restriction for the group with appropriate where clause.
    3)At a later point, the above rows will be opened to NY_SALES_EXTERNAL group also.
    This same concept holds good a number of jurisdiction (more or less static) and a dynamic number of LineIDs. So, if 10000 rows of data corresponding to new LineID 999 and Jurisdiction AK are in the table now, they are initially accessible only to AK_SALES_ADMIN group only. No one else should be able to access it.
    Results:
    1) With the way I laid out the business rules above, I am ending up with 528 groups.
    2) There is a restriction created for a unique combination of Jurisdiction and LineID for each table.
    Problems/Questions:
    How can I restrict access to the new rows to one group only. I know that I can let a certain group only look at certain data but how can I restrict that all others cannot look at the same.
    AK_SALES_ADMIN can look at LineID=999 and Jurisdiction='AK'.
    Do I use an Everyone group based restriction? If so, my Everyone group will end up with tons of restrictions. How will they be resolved in terms of priority.
    Am I even thinking of this the right way or is there a more noble way to do this?
    Regards

    the connectinit setting should look something like this:
    declare a date; begin vpd_setup('@VARIABLE('BOUSER')'); Commit; end;
    The vpd_setup procedure (in Oracle) should look like this:
    CREATE OR REPLACE procedure vpd_setup (p_user varchar)IS
    BEGIN
      DBMS_SESSION.set_vpd( 'SESSION_VALUES', 'USERID', p_user );
    END vpd_setup;
    Then you can retrieve the value of the context variable in your vpd functions
    and set the vpd.

  • Where to download sql server 2012 upgrade advisor

    Hi,
    I want to download sql server 2012 upgrade advisor. But http://download.microsoft.com/download/F/E/D/FEDB200F-DE2A-46D8-B661-D019DFE9D470/ENU/x64/sqlua.msi link does not work. It says connection timed out. Can anyone tell me where can I download this?
    Thanks,
    Preetha

    The link
    http://download.microsoft.com/download/F/E/D/FEDB200F-DE2A-46D8-B661-D019DFE9D470/ENU/x64/sqlua.msi
    works for me.
    Kalman Toth Database & OLAP Architect
    SQL Server 2014 Design & Programming
    New Book / Kindle: Exam 70-461 Bootcamp: Querying Microsoft SQL Server 2012

  • Where to download SQL Server 2008 R2

    We have a license for SQL Server 2008 R2 Enterprise, but lost the installation disk.  We are moving to a new updated server.  Where can I download the software?  Can only find links for 2014 now.
    Thanks.

    Hello,
    You can still download evaluation edition from the following URL.
    http://sqlserver.dlservice.microsoft.com/download/9/C/0/9C036510-3218-4258-8B03-67DC1D6A497C/SQLFULL_ENU.iso?lcid=1033
    Then provide the key you have on the Product Key page of SQL Server setup.
    Hope this helps.
    Regards,
    Alberto Morillo
    SQLCoffee.com

  • Where to put SQL Server JDBC driver in Tomcat?

    Can anyone tell me where should I put the Microsoft SQL Server JDBC driver in the Tomcat and can make it work?

    You may also need to place the full path in the classpath variable. You can also download install instructions from the same page where you access the microsoft driver.

  • Adding a custom rendering extension to SQL Server Reporting Services 2012 for SharePoint 2010 integrated mode

    We are attempting to add OfficeWriter report rendering extensions for SSRS 2012 in SharePoint (2010) integrated mode through powershell. The documentation for “New-SPRSExtension” is rather
    sparse and we have not found any clear examples on the internet. With SSRS 2012 in native mode, we make the following two changes to the config files:
    We add the following report rendering extension declaration to
    RSReportServer.config:
    <Configuration>
        <Extensions>
            <Render>
                <Extension Name="XLTemplate" Type="SoftArtisans.OfficeWriter.ReportingServices.ExcelTemplateRenderer,
    SoftArtisans.OfficeWriter.RS2008"/>
                <Extension Name="WordTemplate" Type="SoftArtisans.OfficeWriter.ReportingServices.WordTemplateRenderer,
    SoftArtisans.OfficeWriter.RS2008"/>
            </Render>
        </Extensions>
    </Configuration>
    We add the following security trust codegroup to
    RSSvrPolicy.config:
    <configuration>
        <mscorlib>
            <security>
                <policy>
                    <PolicyLevel version="1">
                  <CodeGroup version="1" PermissionSetName="Nothing">
                    <CodeGroup
                                version="*"
                                PermissionSetName="FullTrust"
                                Name="SoftArtisans_OfficeWriter_Strong_Name"
                                Description="This
    code group grants SoftArtisans OfficeWriter code full trust.">
                              <IMembershipCondition
                                class="StrongNameMembershipCondition"
                                version="*"
                                PublicKeyBlob="00240000048000009400000006020000002400005253413100040000010001004779CB207F11
                                5E86EF9DD3233F9F130F8891911345176650F72330F84CA3F54C96DEB08439680660F02872EEF5DA3955
                                A14C63F96E57DFB71B1535280C37DA2CB5BA37D78A9882414DB11F67FD66DEBC4AD93DD34F4A587D34D
                                B4D23D9C6AF83431D88A7EF42BB01082913F3560DCB50129C5BBA7ECA0DE8BC286DA74F58FADE"/>
                  </CodeGroup>
              </CodeGroup>
           </PolicyLevel>
        </policy>
       </security>
      </mscorlib>
    </configuration>
    What would be the equivalent syntax for “New-SPRSExtension” to do the above for SSRS 2012 in SharePoint (2010) integrated mode?
    Alison Bird SoftArtisans Technical Services www.softartisans.com

    Hi Alison,
    Unlike the deployment of other custom extensions such as custom delivery extension and data processing extension, it is not necessary to add a code group for the custom assembly that grants FullTrust permission for the extension during the deployment of
    custom rendering extension. If you have copy the custom assembly to the %ProgramFiles%\Microsoft SQL Server\MSRS11.<InstanceName>\Reporting Services\ReportServer\Bin folder, and modify the RSreportserver.config file to add the extention entry properly,
    please open the SSRS Service Application created on the SharePoint and verify that your extension is included in the list of available export types for a report.
    Reference:
    Deploying a Rendering Extension
    Regards,
    Mike Yin
    TechNet Community Support

  • Equivalent of "connect by " clause in SQL Server's T/SQL to get family tree branches

    Is there any equivalent command in SQL Server's T/SQL for the command :-
    select parent, offspring from table_family start by offspring='child1' connect by parent=PRIOR offspring

    Is there any equivalent command in SQL Server's T/SQL for the command :-
    select parent, offspring from table_family start by offspring='child1' connect by parent=PRIOR offspring I had this problem some time ago. I don`t found an eqivalent on MS-SQL-server 7.0. So I wrote a T-SQL procedure wich calls itself recusively. ( I don`t have the souce-code any more ).
    I don4t know if there is an equivalent on MS-SQL-server 2000.

  • Where is the SQL server data Tools on SQL2014 Express .. ?

    Hi,
    I have installed the SQL2012 Express which bundle a Visual Studio 2010 Shell so I can build some Reports
    However, when I install the SQL2014 Express (SQLEXPRADV_X64_ENU) , the SQL Server Data Tools no longer exists (I try to manual run it but it said "Invalid license data. Reinstall is required"
    Please advise which Visual Studio I should install in order to build some Report and publish to the SQL2012/2014 SQL reporting server .. ?!
    Thanks

    You can get SSDT here:
    Download SQL Server Data Tools
    Olaf Helper
    [ Blog] [ Xing] [ MVP]

  • Where to install SQL Server PowerPivot for SharePoint?

    The environment is SharePoint 2013 Enterprise Edition and SQL Server 2012 SP2 Enterprise Edition.  
    SQL Server 2012 SP2 Enterprise Edition is installed as default instance on a dedicated box.   All the features are selected in the Feature Selection windows during installation (see image).
    Now, I need to install SQL Server PowerPivot for SharePoint.   Should it be installed on the same dedicated box?  If I understand correctly, I need to select the SQL Server PowerPivot for SharepPoint option and uncheck
    the checkbox Add SQL Server Database Relational Engine Services to this installation.   Does this option also install SSAS?  Since there is already an existing SSAS, will that cause problem?

    Hi PcSQL66,
    To install SQL Server PowerPivot for SharePoint, you need to select SQL Server PowerPivot for SharePoint
    on the Setup Role page. Please refer to the screenshot below.
    And if you have a SSAS instance installed in your server, install SQL Server PowerPivot for SharePoint will install another SSAS instance.
    For the detail information, please refer to the link below.
    https://msdn.microsoft.com/en-us/library/jj219067(v=sql.110).aspx
    Regards,
    Charlie Liao
    TechNet Community Support

  • How to pass dynamically constructed string to where clause

    select name from mytable
    where l_condition
    and sal=20;
    l_condition is value coming from the function.
    ex: l_condition is first_name='abc' and last_name='xyz' and first_name='def' and last_name='zef'

    Dynamic SQL can help in this case:
    variable ref refcursor
    DECLARE
      l_condition VARCHAR2(1000) :=
          ' salary > 3000  and first_name like ''L%''';
    BEGIN
      OPEN :REF FOR
      ' SELECT first_name, salary FROM hr.employees ' ||
      ' WHERE ' || l_condition;
    END;
    print :ref;
    FIRST_NAME           SALARY                
    Laura                3630                  
    Lindsey              8800                  
    Lex                  18700                 
    Luis                 7590                  
    Louise               8250                  
    Lisa                 12650                 

  • Where clause in sql query for updateable report

    Why is the following not working as source for an updateable report ?
    select customer_name from temp_customers
    where customer_type = :my_field;
    How can I make a filter for an updateable report that is based on a field on my page ?
    Greetings Bernd

    Howard,
    The htmldb_item API package allows you to display column values in a report as HTML form fields. You have a choice of different types of form fields. In your example for instance you get a select list by using the function select_list_from_lov. But by simply placing form fields in an HTML page, you don't specify that those fields are actually supposed to update data in a database. You need an after submit process that is actually performing the update.
    You can implement this type of process manually using your own PL/SQL code. Or you can have HTML DB do this for you. If for example you were using the tabular form wizard, you would get an updateable report, including the update process and even including checksum functionality to make sure that you don't overwrite another person's changes (lost update detection).
    If you use the wizard, the report form items use the build-in display types. This means you don't have to do your own calls to htmldb_item as part of your query. It is generally advisable to use the build-in types as they are easier to work with and are only rendered for the rows actually shown as opposed to be rendered for the entire result set.
    If you do choose to use htmldb_item, you'll have to code your own PL/SQL code to perform the updates and you should also include some logic for lost update detection. The HTML DB documentation provides information on how to manually process data from tabular forms.
    Hope this clarifies your question about updateable reports,
    Regards,
    Marc

  • How to write a java function for use in where clause in SQL statement

    Hi,
    Does anyone know a good tutorial on how to write and include a Java class/function into Oracle.
    I'd like to write mathematical function to use in my queries, but the resources available in PL/SQL are very limited.
    Many thanx

    Pim,
    I see you got an answer in the PL/SQL forum.
    But in case you haven't seen it, perhaps this Web page will help:
    http://www.oracle.com/technology/tech/java/jsp/index.html
    Good Luck,
    Avi.

  • SQL Server "LEFT OUTER JOIN" syntax

    Haven't seen a solution to this on the forum or in the docs.
    I've got 2 objects, Task and Role, that are linked in a M-M relationship.
    My tables are:
    T_TASKS
    T_TASKSROLES
    T_ROLES
    I am querying T_TASKS and joining on T_ROLES, but I need to use an outer join on T_ROLES.
    In SQL Server, my FROM clause SHOULD look like this:
    FROM (T_TASKSROLES t2 LEFT OUTER JOIN T_TASKS t1 ON t1.ID = t2.TASKID) LEFT OUTER JOIN T_ROLES t0 ON t0.ID = t2.ROLEID
    however, if I use eb.anyOfAllowingNone(_roles) in my ExpressionBuilder. TopLink creates a LEFT OUTER JOIN clause that looks like this:
    FROM T_ROLES t0 LEFT OUTER JOIN T_TASKS t1 ON ((t0.ID = T_TASKSROLES.ROLEID) AND (t1.ID = T_TASKSROLES.TASKID))
    I can see the logic in how it builds this clause. But, it doesn't parse in SQL Server.
    Is there a way to effect how TopLink generates the FROM clause for outer joins? I mean, I understand how to use the XXXPlatform.java source files and can change whether to use OuterJoin in the WHERE clause or not. But, I can't see anything in the platform class that would allow me to figure this out.
    I realize I could write SQL manually, but is there a way to do this so that the same code would work on SQL Server, Oracle, and Sybase (assuming the DatabaseLogin is configured appropriately)?
    It just seems like LEFT OUTER JOIN when joining M-M relationships isn't generating proper SQL. Is the TopLink SQL SQL92-compliant?
    Nate

    I should add that I have tried to change SQLServerPlatform to have shouldPrintOuterJoinInWhereClause() return "true". This embeds a "=*" in the join conditions in the WHERE clause.
    SQL Server 2000 still supports this syntax, but the "=*" isn't ALWAYS the correct operator. It is IMPORTANT to put the "*" on the correct side of the expression.
    TopLink always prints "=*", and it always puts it in the correct space, but the OPERATORS are not always in the correct order so you are creating a "left join" on the wrong table.
    So my other question, is it possible to FORCE TopLink to remember to put the outer join table in the RIGHT SIDE?
    Nate

  • Dynamic query in where clause while looping in an internal table.

    Hi,
    Had a small question : How can i make a dynamic query for the WHERE clause while looping at an internal table.
    i want to implement a dynamic where clause query for the below example.
    it_cfx_col is an internal table and wa_cfx_col is a work area for it_cfx_col
      DATA :
      i_cfx_col TYPE TABLE OF cfx_col,
      wa_cfx_col LIKE LINE OF i_cfx_col.
    DATA : count TYPE i VALUE 0.
    DATA : l_where_clause TYPE string,
             l_where_clause2 TYPE string,
             l_name type string.
    l_name = 'NANDANOM'.
    l_scenario = 'collaboration'.
    LOOP AT it_cfx_col INTO wa_cfx_col
    WHERE CREATED_BY = l_name
    AND SCENARIO = l_scenario.
    count = count + 1.
    some business logic implemented using the work area wa_cfx_col
    endloop.
    Now i want to write a dynamic query for the where clause.
    DATA : count TYPE i VALUE 0.
      DATA : l_where_clause TYPE string,
             l_where_clause2 TYPE string,
             l_name type string.
    l_name = 'NANDANOM'.
    l_scenario = 'collaboration'.
      l_where_clause = 'CREATED_BY = l_name'.
      l_where_clause2 = 'AND SCENARIO = l_scenario'.
    if l_scenario is not initial.
      CONCATENATE  l_where_clause l_where_clause2
      INTO l_where_clause SEPARATED BY space.
    endif.
    LOOP AT i_cfx_col INTO wa_cfx_col
    WHERE (l_where_clause).
    count = count + 1.
    some business logic implemented using the work area wa_cfx_col
    endloop.
    when i compile this i get an error message as { Statement concluding with "...(l_where_clause)" ended unexpectedly}
    Even i changed the initilization of the variable  l_where_clause2 to [ l_where_clause2 = 'AND SCENARIO = l_scenario.'. ]
    added the end of line demarkation ".", but still i got the same error message.
    Is it a limtation in ABAP that i cannot write a dynamic query for the where clause while looping at an internal table?
    Regards,
    om

    Hi savita,
    there in no such 1 limitaion in abap for dynamic query .. i think the  error meassge is only beacuse of your synatx delcartaion.
    >> LOOP AT i_cfx_col INTO wa_cfx_col
       WHERE (l_where_clause).
       count = count + 1.
    some business logic implemented using the work     area    wa_cfx_col
       endloop.
    afted delclarataion also , in the where statement you should specify both the field name and value bname
       LOOP AT i_cfx_col INTO wa_cfx_col
       WHERE l_where_clause = 'CREATED_BY = l_name' .
       count = count + 1.
    hope it helps.
    regads
    priya.

Maybe you are looking for

  • Account groups in Chart of account

    Hello guys.... When I tried to define the revenue account in FS00 it is throwing a message saying... " The account groups are not defined in chart of accout XXXX " So, How to define the account groups in a chart of account? Thanx in advance. regards

  • Method for colouring particular cell

    Hello friends,              I displayed the output in grid using the class "CL_GUI_ALV_GRID". Now i need to colour the particular cell with different colours based on the condition.What is the method used for that. If possible give an example code. T

  • With seamlesstabbing unchecked, how to leave the capitvate swf file?

    Hi, I have a captivate project which is in a popup window and with a link after the captivate swf file. I have the seamlesstabbing unchecked so user may tab through and focus in the swf. And I want at the last slide, user can leave the captivate swf,

  • Logo in email signature

    I have my email signature set up. I copied and pasted it from another message. Unfortunately, it did not and will not incorporate my company logo. Any solution? It's quite annoying. Thanks.

  • Nook not showing up in devices on ADE

    I've downloaded ADE onto my computer, authorized it, downloaded a book,  but when I try to sync it to my Nook it is not listed under devices. There isn't even a devices area listed, just library. I've tried syncing a bunch of times. Even deleting ADE