Parameterized IN Clause In Dynamic SQL

Nov 16, 2007

Hi,

I am trying to build a parameterized query where I pass a set of integer values into the dynamic sql. Please see below example.

DECLARE @SQLQUERY NVARCHAR(4000)
DECLARE @PARAMDEF NVARCHAR(1000)
DECLARE @VALUES VARCHAR(100)

SET @PARAMDEF = N'@IN_VAL VARCHAR(100)'

SET @VALUES = '1,2,3,4'

SET @SQLQUERY = 'SELECT * FROM TABLEA WHERE COLUMNA IN (@IN_VAL)'

EXEC SP_EXECUTESQL @SQLQUERY,@PARAMDEF,@IN_VAL=@VALUES

This fails with the error "cannot convert varchar to numeric". I believe since ColumnA is numeric, its trying to convert the dynamic paramter to numeric leading to the failure.

has someone implemented an In clause as a parameter? Please do not tell me that I can append the values as string and construct a dynamic query. I want to use a parameterized version. I will be calling this repeatedly and dont want recompile overhead.

TIA

View 7 Replies


ADVERTISEMENT

Parameterized Where Clause

Jul 5, 2005

Hello,I have an add stored procedure in Yukon (would work in 2000 too), where I select the ID from the table to make sure that it doesn't already have the data.  So it looks like:create procedure ....set transaction isolation level serializablebegin transactiondeclare @ID   intselect @ID = rowid from tblBusinessInformation where Name = @Name and Rules = @Rulesif ( @ID is NULL ) begin   insert into tblBusinessInformation (..) values (@Name, @Rules) endcommit transactionThe problem is the values could be:Name   RulesNULL   'Test''Test'      NULL'Test'      'Test'When one of the values was NULL, it would never select the ID, unless I changed it to "where Name is @Name", and then it worked, because where Name is NULL, which is correct in SQL; so how do I allow for both; I can use the CLR, but would like to avoid rewriting the proc if possible, and I thought that was to work...Thanks.

View 3 Replies View Related

Parameterized SP In WHERE Clause Of Another SP

Jun 6, 2006

I've got this SP:CREATE PROCEDUREEWF_spCustom_AddProfiles_CompanyYear@prmSchoolYear char(11)ASSELECTContactIDFROMdbo.EWF_tblCustom_CompanyProfileWHERESchoolYear = @prmSchoolYearI'd like to be able to reference that in the where clause of anotherSP. Is that possible?I'd like to end up with something like this:CREATE PROCEDUREMyNewProc@prmSchoolYear2 char(11)ASSELECTContactID, SomeOtherFieldsFROMtblContactWHEREContactID IN (exec EWF_spCustom_AddProfiles_CompanyYear@prmSchoolYear2)How would I make that happen?If this isn't possible, what else might I try?Thanks much for any pointers.JeremyPS: I accidentally crossposted this in another group(http://tinyurl.com/gksq4) thinking it was this one. Sorry for that.

View 1 Replies View Related

How To Use Parameterized Queries With IN Clause

Feb 5, 2008

Hi,
I need to use parameters with the IN clause in a SQL statement like:
select * from tableX where field IN (1,2,3,4)
I don't know how to do that.
I'm using SQLServer and OleDB.
 
Thanks for your help.
 

View 1 Replies View Related

Using DTS Parameterized Query 'IN' Where Clause

Apr 30, 2002

I want to export an SQL Server table to an Excel Spreadsheet driven by a web interface.
I am using Cold Fusion to call a SQL Server Stored procedure. The SP accepts a variable (IDlist) from the web page and sets this to a Global Variable.

EXEC @hr = sp_OASetProperty @oPKG, 'GlobalVariables("outIDlist").Value', @outIDlist

The SP then executes a DTS package to export to Excel. The DTS package uses the Global variable in the SQL Query thus:

SELECT ...
FROM ...
WHERE tblPropertyRegister.IDProperty IN (?);

This works fine when I pass one single ID (@outIDlist = "20") into the stored procedure.
But it returns no records when I pass multiple IDs (@outIDlist = "19, 20, 21") into the stored procedure. It works fine also if I "hard code" the IDlist into the DTS query (eg WHERE tblPropertyRegister.IDProperty IN (19, 20, 21);).
The problem appears to be in the setting of the global variable in the stored procedure.

Has anyone had any experience with this? Any feed back would be greatly appreciated. TIA

Alan

View 2 Replies View Related

SQL Server 2012 :: Using Parameterized Query With Like In Where Clause

Feb 4, 2014

From MS Dynamics NAV 2013 I get a lot of querries that have a where clause like this:

where [Field1] like @p1 and [Field1] < @p2.
Field1 is the only primary key field and clustered index. The query also has a TOP 50 clause.
@p1 is always a "Starts-With"-value (something like N'abc%').

The query plan uses a clustered index seek but the number of reads look more like a clustered index scan.

Depending on the table size I see 1M or more reads for these querries.

If I rebuild the query in SSMS, but replace the paramerters with actual values I only see a few reads.

I was able to reproduce the issue with a temp table. See code below.

Is there a way to make SQL Server use another strategy when using the parameterized query?

SQL Server Version is 11.0.3401.
if object_id('tempdb..#tbl') is not null
drop table #tbl;
create table #tbl
(
[No] nvarchar(20)
,[Description1] nvarchar(250)

[Code] ....

View 9 Replies View Related

Parameterized Order By Clause: Doesn't Work

Jul 23, 2005

Can someone tell me why SQL seems to ignore my order by clause?I tried to run through the debugger, but the debugger stops at theselect statement line and then returns the result set; so, I have noidea how it is evaluating the order by clause.THANK YOU!CREATE proc sprAllBooks@SortAscend varchar(4),@SortColumn varchar(10)asIf @SortAscend = 'DESC'Select titles.title_id, title, au_lname, au_fname,Convert(varchar(12), pubdate, 101) as PubDatefrom authorsinner jointitleauthoronauthors.au_id = titleauthor.au_idinner jointitlesontitleauthor.title_id = Titles.title_idORDER BY au_lnameCASE @SortColumn WHEN 'title' THEN title END,CASE @SortColumn WHEN 'au_lname' THEN au_lname END,CASE @SortColumn WHEN 'PubDate' THEN PubDate ENDDESCELSESelect titles.title_id, title, au_lname, au_fname,Convert(varchar(12), pubdate, 101) as PubDatefrom authorsinner jointitleauthoronauthors.au_id = titleauthor.au_idinner jointitlesontitleauthor.title_id = Titles.title_idORDER BYCASE @SortColumn WHEN 'title' THEN title END,CASE @SortColumn WHEN 'au_lname' THEN au_lname END,CASE @SortColumn WHEN 'PubDate' THEN PubDate ENDGO

View 7 Replies View Related

Dynamic Table Name In Parameterized Ole Db Source Query?

Sep 11, 2006

hi everyone,

joy mundy alluded in her webcast that it is possible to dynamically specify a table name in a parameterized ole db source query. is this true? if so, how can it be done?

View 6 Replies View Related

Dynamic Parameterized MDX Dataset In Report Table

Oct 10, 2007

Hi, I was wondering if there is a way to solve this issue.

I have the following MDX to retrieve specialised time related data from a cube



Code Block

SELECT NON EMPTY { { { [Measures].[% Vacancy], [Measures].[Total Square Area], [Measures].[Deliveries], [Measures].[Net Absorption] } * { [Time].[Quarter].[2007 Q1], [Time].[Quarter].[2007 Q1].lag(1), [Time].[Quarter].[2007 Q1].lag(2), [Time].[Quarter].[2007 Q1].lag(3), [Time].[Quarter].[2007 Q1].lag(4), ytd( [Time].[Quarter].[2007 Q1]), ytd( [Time].[Quarter].[2007 Q1].lag(4)),ytd([Time].[Quarter].[2007 Q1].parent.lag(1)),ytd([Time].[Quarter].[2007 Q1].parent.lag(2)) } } } ON COLUMNS ,

NON EMPTY { DESCENDANTS( [Location].[All Location], [Location].[Market] ) } ON ROWS

FROM [QMS]

WHERE ( [Overall].[Overall].&[Y] )






I can populate a table with the columns i need from the resulting dataset, however it is not dynamic. i.e.

The dataset field names come up as say,

Measures___Vacancy_Time_All_Time_2007_2007_Q1
Measures___Vacancy_Time_All_Time_2006_2006_Q4

Which i can place in the report...

But if I then want to parameterize [2007 Q1] like as follows




Code Block
="SELECT NON EMPTY { { { [Measures].[% Vacancy], [Measures].[Total Square Area], [Measures].[Deliveries], [Measures].[Net Absorption] } * { [Time].[Quarter].[" + Parameters!Quarter.Value + "], [Time].[Quarter].[" + Parameters!Quarter.Value + "].lag(1), [Time].[Quarter].[" + Parameters!Quarter.Value + "].lag(2), [Time].[Quarter].[" + Parameters!Quarter.Value + "].lag(3), [Time].[Quarter].[" + Parameters!Quarter.Value + "].lag(4), ytd( [Time].[Quarter].[" + Parameters!Quarter.Value + "]), ytd( [Time].[Quarter].[" + Parameters!Quarter.Value + "].lag(4)),ytd([Time].[Quarter].[" + Parameters!Quarter.Value + "].parent.lag(1)),ytd([Time].[Quarter].[" + Parameters!Quarter.Value + "].parent.lag(2)) } } } ON COLUMNS ,NON EMPTY { DESCENDANTS( [Location].[All Location], [Location].[Market] ) } ON ROWS FROM [QMS] WHERE ( [Overall].[Overall].&[Y] )"





so that everything is then driven from a single selected Quarter value, the table report no longer gets populated, as it has hardcoded field values such as

=Fields!Measures___Vacancy_Time_All_Time_2007_2007_Q1.Value

and if the Quarter selected is [2006 Q1] for example, this field will not exist in the dataset.

Is there a way to accomplish this? I am using SSRS 2005 against SSAS 2000 cubes

View 5 Replies View Related

Dynamic Select Statement Using Parameterized SqlCommand Or Multiple Possible .CommandTexts

Jul 30, 2007

I'm trying to create an interface for filtering profiles from an SQLServer 2005 database using an html form. The form allows filtering based on a minimum level required in between one and four different columns. The first (and only mandatory) column to be filtered on has its name hard-coded into the base query. In trying to get the other three possible criteria to work, I've taken several approaches, all of which failed.The other three potential criteria are selected from a drop down menu on the form and ideally these choices are passed into a query to be used as column names. My first attempt looked like this:    query = "SELECT * FROM profiles_tbl WHERE (EngSkill >= @english)"    ....    if ReqSkill1 <> "" then                level1 = Convert.ToInt32(Request.form("minskilllvl1"))                query = query & pickclmleft & ReqSkill1 & pickclmright1                cmd.Parameters.Add("@ReqSkill1", SqlDBtype.text)                cmd.Parameters("@ReqSkill1").value = ReqSkill1                cmd.Parameters.Add("@level1", SqlDBtype.int)                cmd.Parameters("@level1").value = level1    end if   above If statement was repeated for 2nd and 3rd optionsSecond approach was to remove all parameters from sections of the query that were appended onto the original statement. This involved lots of strings containing AND clauses with hard-coded column names which were appended on when the corresponding option was selected in the form. Code looked like this:     query = "SELECT * FROM profiles_tbl WHERE (EngSkill >= @english)"     ASPqry = " AND (ASPlevel >= "    try             con = new SqlConnection()            con.ConnectionString = “**************string was correct****************â€?                        cmd = new SqlCommand()            cmd.Parameters.Add("@english", SqlDBtype.int)            cmd.Parameters("@english").value = english                                    if ReqSkill1 <> "" then                if ReqSkill1 = "ASPlevel" then                    query = query + " AND (ASPlevel >= "                    level1 = Convert.ToInt32(Request.form("minskilllvl1"))                    if level1 = 0 then                        query = query + "0)"                    end if                    if level1 = 1 then                        query = query + "1)"                    end if                    if level1 = 2 then                        query = query + "2)"                    end if                    if level1 = 3 then                        query = query + "3)"                    end if                end if            end ifFinally when this too failed, I created four entirely separate queries, detected how many criteria were used, and used the appropriate query, passing necessary skill level in as a parameter. I'll provide code if needed here. Queries were written as strings and then used to set the CommandText property for an SqlCommand variable. I think it's important to note that in all cases the most basic version of the query worked. In the first, if only the first criteria was used the statement executed fine. Same in the second. In the third, whatever query could be assigned first (even though only one could be assigned because of logical structure of if statements) worked and none of the others would. This last case was tested even with completely hard-coded queries that SQL Server 2005 validated as correct and would run. Any help is greatly appreciated. Will post as much code as people want/need, and if I can get any one of these methods working I'll be thrilled. I have no need for all three. A.S. Moser 

View 4 Replies View Related

Using Dynamic IN Clause

May 9, 2007

I am looking to do a dynamic IN clause, such as the following.create procedured usp_SPTest

@variable varchar(150)
AS

select * from table
where ID IN (@variable)
GO

Then execuuting this withusp_SPTest '''1'',''2'''
Basically this won't work and gives an error
Syntax error converting the varchar value ''1','2'' to a column of data type int.
which makes sense. Is there anyway to do this outside of a dynamic SQL statement?
According to http://www.sommarskog.se/dynamic_sql.html#List it doesn't look promising but unpacking the list into a table is a bit over board for this in my opinion. Any help is appreciated.

View 3 Replies View Related

Need Help With Dynamic Where Clause

Jul 19, 2007

Hi. I can't seem to get my dynamic where clause right.

The pseudo code is such:

when gender is not null and is not 'show all' then create the condition "when tab1.gender = @gender".
and, when country is not null and is not 'show all' then create the condition "when tab1.country = @country".
and, finally, create the condition where tab1.bday_year is
between @toage AND @fromage (this will never be empty or null).

I have tried many variations, the most recent being below.
But, the resulting data does not act as it should (or it won't compile) :


Code:


WHERECASEWHEN @gender <> 'show all' THEN tab1.gender = @gender
WHEN @country <> 'show all' THEN tab1.country = @country
tab1.bday_year BETWEEN @toage AND @fromage END



thanks for any suggestions provided.

View 6 Replies View Related

Dynamic 'where' Clause

Nov 13, 2006

HiI need some advice on which direction to take!Consider this statement:SELECT business_name FROM myTable WHERE town = @town AND county = @countyMy problem is that i will not always have the @county variable available. Is there a way to use an IF or a CASE inside the SQL statement (i know i can create two seperate sql statments but dont want to do it this way)? If it makes it easier, when the @county variable is not available, it has a value of 0.thanks againPs, i also know how to do it using dynamic sql using the EXEC() command, but i'd prefer to steer clear of this method also.

View 5 Replies View Related

Dynamic WHERE Clause

Dec 6, 2007

Hi all,

I pass a WHERE clause to a sp and use EXEC to execute it. it works fine if it does not include datetime Type in WHERE clause. however, if it did, the an error will be shown up "Unclosed quotation mark after the character string '2'.". I try to copy that clause and run as query in SQL server. there is no problem.

the Where clause is (Status='Open' or Status='On Going' or Status='Hold' or Status='Close') And (Found_Date BETWEEN ' '2007-11-01'' And ''2007-11-30'')

View 20 Replies View Related

Dynamic Where Clause

Sep 18, 2007

Hello everyone,

I want to build a dynamic where clause which makes :

WHERE column1 = (@parameter1 if @parameter1 is not null) / (anything if @parameter1 is null)

Basically I do not know how to set column1 = ANYTHING

Best regards and thanks.

View 5 Replies View Related

Dynamic Where Clause

Aug 23, 2007

I am trying to write a stored procedure usp_select using dynamic sql to select from a table. The stored procedure will accept the where clause and/or the where clause parameters. I have tried 3 different methods -

Method 1 -
exec usp_select @whereCondition='col1 like ''abc%'' and col2 = ''xyz'''
In usp_select, I'll build and execute the sql like -
set @sql = N'select * from table ' + @whereConition
exec sp_executesql @sql
(basically @sql becomes - select * from table where col1 like 'abc%' and col2 = 'xyz')

Method 2 -
exec usp_select @whereCondition='col1 like @p1 and col2 = @p2', @WhereParams='@p1=abc%,@p2=xyz'

In usp_select, I'll parse out the values in @WhereParams and then build and execute the sql like -

set @sql = N'declare @p1 nvarchar(10),
@p2 nvarchar(10);
set @p1 = ''' + @parsedValue1 + ''', @p2 = ''' + @parsedValue2 + '''; ' +

N'select col1 from table1 ' + @whereCondition

exec (@sql)

(basically @sql becomes - declare @p1 nvarchar(10), @p2 nvarchar(10);
set @pt = 'abc%', @p2 = 'xyz';
select col1 from table1 where col1 like @p1 and col2 = @p2)


Method 3 -

similar to Method 2 but exec(@sql) will be structured to become -
exec(declare @vparam nvarchar(100), @p1 nvarchar(10), @p2 nvarchar(10);

set @vparam='@p1 nvarchar(10), @p2 nvarchar(10)'

set @p1 = 'abc%', @p2 = 'xyz';

execute sp_executesql N''select col1 from table1 where col1 like @p1 and col2 = @p2', @vparam, @p, @p2)

When I run sql profiler on the 3 methods, method 1 and 2 always result in a Cache Miss on the entire sql structure.
On method 3, a Cache Miss always occurs on the first part of the sql, ie, the first 3 lines where I declare and set the variables. Then a Cache Hit will happen on the execute sp_executesql part.

Do I have any performance gain using method 3 with both a Cache Miss and a Cache Hit?

I hope this is not too confusing. Because I do not know the where condition to the select procedure and hardcoding the values as in method 1 always results in a Cache Miss, therefore, I come up with the ideas in Method 2 and 3.

Any advice would be appreciated.

View 5 Replies View Related

Dynamic Where Clause

Jan 29, 2008



I have a table (tblRestore) that has the following data
FilePath Included FileType
C:DataProjectsBeacon 1 Directory
C:DataProjectsBeaconPDA 1 Directory
C:DataProjectsBeaconBeaconVisual Studio 2005 0 Directory
C:DataProjectsBeaconVisual Studio 2005 0 Directory
C:DataProjectsBeaconPDAAuditPDAWM5 0 Directory


I want to use the data in this table to dynamically create a where clause that would look like this


WHERE (ParentDirectory + '' LIKE 'C:DataProjectsBeacon\%'
OR ParentDirectory + '' LIKE 'C:DataProjectsBeaconPDA\%')


AND (ParentDirectory NOT LIKE('C:DataProjectsBeaconVisual Studio 2005%')

AND ParentDirectory NOT LIKE('C:DataProjectsBeaconBeaconVisual Studio 2005%')

AND ParentDirectory NOT LIKE('C:DataProjectsBeaconPDAAuditPDAWM5%')

)

Can I do this using Sql (Sql Compact 3.0)?

thanks,

View 1 Replies View Related

Dynamic Where Clause

Mar 10, 2008

Hi

I'm using SQL Server 2000...

In a stored procedure I am trying to use a parameter in a where clause which is set dependent upon another parameter... ie if report 1 is run, I want to evaluate against the StartDate field ... otherwise evaluate against the EndDate field.

declare @StartDt datetime;
declare @EndDt datetime;
declare @WhereDate varchar(30);

if @report = 1 then
begin

set @WhereDate = 'Table.EndDate'
end
else set @WhereDate = 'Table.StartDate'

select *
from MyTable
Where @WhereDate >= @StartDt and @WhereDate < @EndDt


I'm getting syntax errors, so my question is.... is it possible... if so what syntax should I use?

Cheers

Jon

View 8 Replies View Related

WHERE-Clause With Dynamic Field?

May 21, 2007

Hi,
i have a stored procedure like this:
 CREATE PROCEDURE dbo.spQuery1

@dynamicField nvarchar(10)

AS

SELECT id, productName, productDescription

FROM products

WHERE @dynamicField = 'True'

RETURN   
The products table has id, productName, productDescription, property1, property2, property3 fields
So my query variable should be, for example, "property1" and the result should be every row with "property1" set to true... but it doesnt work with the sql like this...
 any help?

View 8 Replies View Related

Build Dynamic WHERE Clause

Apr 14, 2008

I have a stored procedure which expects one parameter @Company
The variable @Company holds pipe delimited value: "CNN|AOL|ABC"

I need to build a WHERE clause by parsing @Company value, so the select will look like below:

SELECT *
FROM Company
WHERE CompanyID IN (SELECT DISTINCT(CompanyID) FROM v_Company WHERE CompanyName = 'CNN')
AND CompanyID IN (SELECT DISTINCT(CompanyID) FROM v_Company WHERE CompanyName = 'AOL')
AND CompanyID IN (SELECT DISTINCT(CompanyID) FROM v_Company WHERE CompanyName = 'ABC')

Thanks for your help

View 2 Replies View Related

Dynamic WHERE Clause Alternative.

Jun 26, 2007

I have 3 tables: Authors, Employee and Stores.
I need to create a stored procedure which will take 3 comma delimited parameters, to be able to query above 3 tables.
Basically my front end user can say give me Authors with last name starting from ‘A,B’ and Employee with first name starting from ‘J,N,K’ and Stores with city starting from ‘New, Los’.
So, stored procedure call will look like this Exec myStoredProcedure 'A,B' , 'J,N,K', 'New,Los' .

My question is, how should I handle WHERE clause in stored procedure if I don’t want it to be a “dynamic WHERE�.

Thank you

View 1 Replies View Related

How To Create Dynamic T-SQL Clause

May 6, 2008

Hi,


I have a project which is need dynamically t-sql clause...I've created interface for the create dynamic t-sql clause.
But the clause should get data from relational database. It needs inner join...so it's very hard to do it..

for example


lkpProduct

id product
1 Mouse
2 Keyboard

3 Modem
4 Monitor


main

id productid

1 4
2 1
3 2
4 3
5 4

You can get this table with 2 ways like this..

1. Select main.id, lkpProduct.product from main,lkpProduct where main.productid = lkpProduct.id
2. Select id, case productid when 1 then 'Mouse'.....end as product from main

mytable

id product
1 Monitor
2 Mouse
3 Keyboard
4 Modem
5 Monitor


My question is; how can i use CASE function dynamically ?? Mouse should get from lkpProduct....I do not want to write long table manually..

I hope it is clear for you..

Regards.

View 4 Replies View Related

Build Dynamic WHERE Clause

Apr 14, 2008

Hello,

I have a stored procedure which expects one parameter @Company
The variable @Company holds pipe delimited value: "CNN|AOL|ABC"

I need to build a WHERE clause by parsing @Company value, so the select will look like below:

SELECT *
FROM Company
WHERE CompanyName = 'CNN'
AND CompanyName = 'AOL'
AND CompanyName = 'ABC'


P.S I know that above select doesn€™t really make sense , but I have a bigger query that would be hard to explain in this topic so I just simplified it.

Thank you

View 8 Replies View Related

Dynamic Where Clause With If..else Or Case

Jun 13, 2006

Hello all...

I am trying rewrite an sp that I have that is considered dynamic cause it builds a where clause based on a bunch of if statements then adds it to the the end of select

i.e

if...@where = @where + ' llll '

if...@where = @where + ' llll '

select @statement = @statement + @where

exec(@statement)

I have rewritten most of it to but I have several conditions that use ' contains' for the condition and I can't get SQL server to recognize an if statement or a case statement.

Is it possible to use either statement inside a where clause??

i.e

where if a = 1 then d=e

else contains(.....)



thanks

View 9 Replies View Related

Dynamic WHERE Clause To Stored Procedure

May 25, 2004

Hi all!
I need to create a stored procedure with a parameter and then send a WHERE clause to that parameter (fields in the clause may vary from time to time thats why I want to make it as dynamic as possible) and use it in the query like (or something like) this:

---------------------------------------------------
@crit varchar(100)

SELECT fldID, fldName FROM tblUsers
WHERE @crit
----------------------------------------------------

Of course this does not work, but I don't know how it should be done, could someone please point me in the right direction on how to do this kind of queries.

cheers!
pelle

View 2 Replies View Related

Dynamic Where Clause In Stored Procedure

Jul 23, 2004

Hi, I have several parameters that I need to pass to stored procedure but sometimes some of them might be null. For example I might pass @Path, @Status, @Role etc. depending on the user. Now I wonder if I should use dynamic Where clause or should I use some kind of switch, maybe case and hardcode my where clause. I first created several stored procedures like Documents_GetByRole, Documents_GetByRoleByStatus ... and now I want to combine them into one SP. Which approach is better. Thanks for your help.

View 1 Replies View Related

Using A UDF To Return Values For A Dynamic WHERE IN () Clause

Mar 2, 2006

Greetings,

I've search around quite extensively on the net and found a few examples that touch on this subject, but the only definitive one that seemed to solve this problem used a temp table in the UDF, which, to my knowledge, is impossible...

The problem is thus:
I want to create either a stored procedure or a user defined function to return a list of values I can intersperse to use in a WHERE AccountID IN (<values>). This way, if someone were to create a new stored procedure and they wanted to either only select accounts with those IDs or perform a NOT IN and use it to filter.

The Solution I'm attempting:
My idea is best represented in psuedo-code:
- Create a Function that stores all account Ids we relate to a particular account type, in this case, let's say accountsids "100, 101, 102, 407" are all accounts we want to consider "cash".
- The function would look something like:
CREATE FUNCTION CashAccountIDs()

RETURNS TABLE

AS

BEGIN
DECLARE TABLE @t1 (account INT)
INSERT INTO @t1 VALUES (100)
INSERT INTO @t1 VALUES (101)
INSERT INTO @t1 VALUES (102)
INSERT INTO @t1 VALUES (407)
RETURN @t1
END

Then I could call this function by doing something such as:

SELECT *
FROM Accounts
WHERE AccountId IN (dbo.CashAccountIds())

I would presumably do this for other collections of accounts as well, so that I would end up with say 5 functions I could call to filter various types of accounts.

Not too certain if I am approaching this the correct way or not, I've been receiving a myriad of errors trying different methods. If I use the function above it tells me "Must declare @t1", so I modified it so @t1 is declared in the RETURNS statement, and the syntax checks then work, but when I attempt to save the function it tells me "Cannot perform alter on fn_cashaccountids because it is an incompatible object type"

(The code I use to generate this error is:
CREATE FUNCTION fn_cashaccountids ()

RETURNS @t1 TABLE (i INT)

AS

BEGIN
INSERT INTO @t1 VALUES (100)
RETURN
END

Hopefully I've provided enough but not too much info to sift through, it seems to me this would be something encountered a bit before.

Any help is very much appreciated.

- Jeff

View 3 Replies View Related

Help With Dynamic Where Clause In Stored Procedure

Aug 20, 2007

I have a stored procedure being called based on user search criteria. Some, the colour and vendor fields are optional in the search so i do not want that portion of the procedure to run.

at this point i keep getting errors in the section bolded below
it never seems to recognize anything after the if @myColours <> 'SelectAll'

CREATE Procedure PG_getAdvWheelSearchResults3
(
@SearchDiameter NVarchar( 20 ),
@SearchWidth NVarchar( 20 ),
@minOffset int ,
@maxOffset int ,
@boltpattern1 NVarchar( 20 ),
@VendorName NVarchar( 40 ),
@myColours NVarchar( 40 )
)
As
BEGIN TRANSACTION
SELECT *, dbo.VENDORS.*, dbo.WHEEL_IMAGES.Wheel_Thumbnail AS Wheel_Thumbnail, dbo.WHEEL_IMAGES.Wheel_Image AS Wheel_Image,
dbo.WHEELS.*, dbo.VENDOR_IMAGES.Vendor_Thumbnail AS Expr1, dbo.VENDOR_IMAGES.Vendor_AltTags AS Expr2
FROM WHEEL_CHARACTERISTICS INNER JOIN
dbo.VENDORS ON WHEEL_CHARACTERISTICS.Vendor_ID = dbo.VENDORS.Vendor_ID INNER JOIN
dbo.WHEEL_IMAGES ON WHEEL_CHARACTERISTICS.Wheel_ID = dbo.WHEEL_IMAGES.Wheel_ID INNER JOIN
FILTER_CLIENT_WHEELS5 ON WHEEL_CHARACTERISTICS.Wheel_ID = FILTER_CLIENT_WHEELS5.Wheel_ID INNER JOIN
dbo.WHEELS ON WHEEL_CHARACTERISTICS.Wheel_ID = dbo.WHEELS.Wheel_ID INNER JOIN
CLIENT_WHEEL_PRICES5 ON FILTER_CLIENT_WHEELS5.Client_ID = CLIENT_WHEEL_PRICES5.ClientId AND
WHEEL_CHARACTERISTICS.Wheel_Char_ID = CLIENT_WHEEL_PRICES5.Wheel_Char_ID INNER JOIN
dbo.VENDOR_IMAGES ON dbo.VENDORS.Vendor_ID = dbo.VENDOR_IMAGES.Vendor_ID
WHERE (dbo.VENDORS.Vendor_Active = 'y') AND (FILTER_CLIENT_WHEELS5.FCW_Active = 'y')
AND (FILTER_CLIENT_WHEELS5.Client_ID = '1039')
AND (WHEEL_CHARACTERISTICS.Wheel_Diameter =@SearchDiameter)
AND (WHEEL_CHARACTERISTICS.Wheel_Width =@Searchwidth)
AND (WHEEL_CHARACTERISTICS.Wheel_Bolt_Pattern_1 = @boltpattern1)

if @myColours <> 'SelectAll'
and WHEEL_CHARACTERISTICS.Wheel_Search_Colour = @myColours
end if


AND (cast(WHEEL_CHARACTERISTICS.wheel_Offset as int(4)) BETWEEN @minOffset AND @maxOffset)

ORDER BY CLIENT_WHEEL_PRICES5.Price asc
COMMIT TRANSACTION
GO

Anyone know how i should word the if...statements?
I have not found anything that works yet.
Thanks

View 2 Replies View Related

Highly Dynamic Where Clause In A Stored Procedure

Apr 23, 2008

I have a situation where I'll need to get results from tables based on totally arbitrary filters. The user can select the field to compare against, the value, the comparison operator, and the boolean operator, so each bit in brackets would be configurable:[field] [>] [value] [and]The user can specify an arbitrary number of these, including zero of them. I like the coalesce function for situations that are a little more structured, but I think I'm stuck generating a dynamic query for this -- please correct e if I'm wrong! 

View 1 Replies View Related

How To Pass Dynamic Parameter To Order BY Clause

Sep 13, 2004

Hi,

I use a DataGrid to show the data, and I want it has a sorting and Paging function,
so I use dataset to collect the data from middle tier function and stored procedure.
I have code in aspx page like BindData(ViewState("SortExpr")).

In the stored procedure I pass SortExpr as parameter as following:

CREATE Procedure Ruying_AutoSearch10
(
@Make varchar(50),
@Model varchar(50) = NULL,
@Condition varchar(20) = NULL,
@Miles float,
@Zipcode varchar(5),
@SortExpr varchar(100)
)
AS

DECLARE @RowCount int
SELECT @RowCount = Count(*) FROM ZIPCodes WHERE ZIPCode = @Zipcode AND CityType = 'D'

if @RowCount > 0
BEGIN
SELECT
z.ZIPCode, z.City, z.StateCode, a.Make, a.Model, a.AutoPrice, a.AutoPrice2, a.AutoYear, a.Mileage, a.AdID, a.ImageURL, dbo.DistanceAssistant(z.Latitude,z.Longitude,r.Latitude,r.Longitude) As Distance
/*
The above functions requires the Distance Assistant.
*/
FROM
ZIPCodes z, RadiusAssistant(@ZIPCode,@Miles) r, AutoAd a
WHERE
z.Latitude <= r.MaxLat
AND z.Latitude >= r.MinLat
AND z.Longitude <= r.MaxLong
AND z.Longitude >= r.MinLong
AND z.CityType = 'D'
AND z.ZIPCodeType <> 'M'
AND z.ZIPCode = a.Zipcode
AND a.AdActive = '1'
AND a.AdExpiredate >= getdate()
AND a.Make = @Make
AND a.Model = IsNull(@Model,a.Model)
AND a.Condition = IsNull(@Condition, a.Condition)
AND dbo.DistanceAssistant(z.Latitude,z.Longitude,r.Latitude,r.Longitude) <= @Miles
ORDER BY @SortExpr
END
ELSE
SELECT -1 As ZIPCode
--ZIP Code not found...
GO


but I got the error as "variables are only allowed when ordering by an expression referenceing
a column name". How I fix this error? Please help.

Thanks.

Lin

View 9 Replies View Related

Stored Procedure With Optional/dynamic Where Clause

Apr 21, 2006

If I do this with a function and multiple inline sql statements, I could probably do it much easier, but here at work, sprocs are required, and I can't seem to stretch my knowledge and Google searches far enough to find the answer. Plus, I don't really think that creating 4 separate sProcs is the most efficient way of doing this
I need to select and return 8 columns from a table, but the problem is I need to feed the sProc parameters in such a way, that I can use different criteria in the Where Clause.
for instance, I need to combine these 4 select statements into one:1. Select (fields) from (table) Where TechID=@TechID and Status=@Status)2. Select (fields) from (table) Where TechID=@TechID3. Select (fields) from (table) Where OrdNum=@OrdNum3. Select (fields) from (table) Where CustNum=@CustNum
In all instances, the fields and the table are the same - how can I combine all these possible Where clauses (if/then - Select Case?) so that it's only one Stored Procedure?
(or, is this even possible?)

View 4 Replies View Related

SQL Server 2012 :: Where Clause In Dynamic Query?

Jul 2, 2015

I am creating a dynamic query where i am appending a where clause something like -

IF (@CurCaptureDate IS NOT NULL)
SET @where_clause = @where_clause + CHAR(10) + 'AND CD.CaptureDate = ' + @CurCaptureDate

PS - CD.CaptureDate is datetime and @CurCaptureDate is also datetime

but when executing , it gives this error - Msg 241, Level 16, State 1, Line 169 Conversion failed when converting date and/or time from character string.

i am not able to use convert here with these quotes.

i tried this - SET @where_clause = @where_clause + CHAR(10) + 'AND CD.CaptureDate = ' + CONVERT(VARCHAR(25),@CurCaptureDate )

but it makes it to -

AND CD.CaptureDate = Jul 19 2014 12:00AM. I would need the date in quotes.

View 4 Replies View Related

Transact SQL :: Writing Where Clause In Dynamic String?

Nov 2, 2015

I am trying to write where clause after pivot but I could not know how?

DECLARE @PivotQuery AS NVARCHAR(MAX)

View 8 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved