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
ADVERTISEMENT
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
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
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
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
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
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
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
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
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
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
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
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
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
View Related
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
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
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
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
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
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
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
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
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
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
May 7, 2015
I have to build a dynamic query to go over to Oracle and get some data and bring it back via a SQL Server Stored Procedure. How I can create an IN clause passing values and ","s from a SQL Server Temp Table that I have already built.
SET @SQLQuery = @SQLQuery + 'WHERE MEMBER.MEMBER_ID IN (''''' + SELECT MEMBER.MEMBER_ID + ',' FROM #TempTable + '''''Â '
View 6 Replies
View Related
Mar 2, 2005
I'm sending a stored procedure a number of parameters, including an int for a foreign key field. I'm trying to dynamically build the Where Clause of the query.
I'm getting the error:
Syntax error converting the varchar value 'wo_dutfk = ' to a column of data type int.
NOTE: wo_dutfk is an int field within the WO table.
Here's the code:
CREATE PROCEDURE dbo.ewo_sp_WOLookup
(
@WODUTFK int=NULL,
@WOENDDATE datetime = NULL,
@WOSTATUS char(10) = NULL,
@DEBUG int=0
)
AS
Declare @intErrorCode int,
@chvQuery varchar (8000),
@chvWhere varchar (8000)
select @intErrorCode = @@ERROR,
@chvQuery='SET QUOTED_IDENTIFIER OFF select * from WO',
@chvWhere=''
-- DUT is specified
If @intErrorCode = 0 and @WODUTFK is not NULL
Begin
set @chvWhere = @chvWhere + 'wo_dutfk = '+@WODUTFK
End
IF @intErrorCode=0 and Len(@chvWhere)>0
Begin
set @chvQuery = @chvQuery + ' WHERE ' + @chvWhere
select @intErrorCode=@@ERROR
END
IF @DEBUG<>0
select @chvQuery Query
IF @intErrorCode=0
Begin
exec (@chvQuery)
select @intErrorCode=@@ERROR
End
return @intErrorCode
GO
---
Any suggestions on how to fix?
Thanks,
peter
View 10 Replies
View Related
May 12, 2015
The first select is running fine but due to extra values added to the table the list of manual difined columns must be added manualy each time new values occur.
Is it possible to make the PIVOT's IN clause dynamicly as stated in the second script (it is based on the same table #source) when running it prompts the next error;
Msg 156, Level 15, State 1, Line 315
Incorrect syntax near the keyword 'select'.
Msg 102, Level 15, State 1, Line 315
Incorrect syntax near ')'.
adding or moving ')' or '(' are not working.......
select *
into #temp
from #source
pivot ( avg(value) for drive in ([C], [D], [E], [F], [G], [H], [T], [U], [V] )) as value
select * from #temp order by .........
versus
select *
into #temp
from #source
pivot ( avg(value) for drive in (select distinct(column) from #source)) as value
select * from #temp order by .....
View 3 Replies
View Related
Aug 18, 2005
Arvind writes "i want to create a stored procedure returns an OUTPUT variable containing the no. of records given by a query, the query being dynamic.
Preferrably the query should also be passed as a parameter to the stored procedure...If not,it should be constructed in the SP and a Part of the where clause is dependant on the value of another variable passed to the SP.
How should the query be constructed, executed, and then the Count(*) value returned?
"WHERE <condition1> AND <condition 2> ;
"AND <condition 2> " may exist or may not exist in the query; it is dependant."
View 1 Replies
View Related
Jul 17, 2015
I'd like to modify the dates within this where clause to be dynamic, building the date depending on the current year, but everything I try doesn't seem to be syntactically correct.
SELECT *
FROM Openquery(LS_CIS, 'select * from BI_WRKFLW_TASKS where (BI_EVENT_DT_TM>=''1/1/2011'' and (BI_NEEDED_DT_TM>=''1/1/2011''))OR (BI_EVENT_DT_TM>=''1/1/2011'' and BI_NEEDED_DT_TM is null)') AS derivedtbl_1
I'd like to replace ''1/1/2011''Â in the where clause with something like:
CAST(CAST(YEAR (GETDATE())-4 AS varchar) + '-' + CAST(01 AS varchar) + '-' + CAST(01 AS varchar) AS DATETIME)
View 9 Replies
View Related
Jul 23, 2007
Dear All;
i want to use a calculated field in where clause but this does'nt works: e.g.;
select (colA + colB) as calcField
from tbl
where calcField > 100
what is the right way to do it, as i m getting error;
it works like :
select (colA + colB) as calcField
from tbl
where (colA + colB) > 100
but i m using a complex query as i m getting value from a function and then i hav to use that in where clause as well ;
Thanx in advance,
--
Muhammad Zeeshan
View 1 Replies
View Related
Feb 5, 2008
I need to do something similar to the following.
Select
a.name,
m.TOTAL_MNTH_INCOME + m.CO_TOTAL_MNTH_INCOME as income1,income1 * 12 as income2,Round(income2, 1000) as income3,income3 / 1000 as income
,a.fielda
,b.filedb
from tablea a, tableb b
where a.name = b.name'
and income <> b.income
I can probably string all 4 of my calculations together and say as income. I just copied it that way since that is how the SAS code is written but my big Q is can I use the derived field income from my calculation in my where statement.
View 8 Replies
View Related
Jun 20, 2001
Hello,
I have this SP that works, except I need to add another field value for the WHERE clause. As you can see I have "WM" but I need to add "PR", and those two are definitely in the table field. I've tried a variety of syntax arrangements using the AND operator, the OR operator, the & operator, just a comma between the two, nothing between the two. Can someone please show me what I'm doing wrong. It fileters for "WM" fine, but I also need it to filter in the WHERE clause for "PR". Here is the SP:
CREATE procedure spDemoSchedule (@beginDate varchar(10), @endDate varchar(10), @storeNum int)
AS
SELECT Progstats.[Program#], Progstats.KCKOFF, Progstats.ProgramName, Progstats.Parent, Store.[Str#], Store.Status, Progstats.Dept, Store.[Program#], Product.[Item#], Product.[Item]
FROM Progstats INNER JOIN Product ON Progstats.[Program#] = Product.[Program#] INNER JOIN Store ON Progstats.[Program#] = Store.[Program#]
WHERE Progstats.KCKOFF BETWEEN @beginDate AND @endDate AND Store.[Str#]=@storeNum AND Progstats.CLASS="WM"
GO
TIA,
Bruce Wexler
View 2 Replies
View Related
Nov 18, 2015
I have a small table named Exclude_Cusno_Item that has a varchar(29)Â field named
ITEM. When I query the table to show all of the records like this:
Select * from Exclude_Cusno_Item
The result set contains a record with 'AAA' in the ITEM field. However, where I write a query with a WHERE clause to select this specific 'AAA' record like this:
Select * from Exclude_Cusno_Item where item = 'AAA'
I get no results. What could be happening that would prevent the 'AAA' record from appearing in the result set of this query? Note that the 'AAA' entry has no trailing or leading blanks.
View 12 Replies
View Related