Transact SQL :: Finding Syntax To Combine IN And CASE In A WHERE Clause?
Oct 29, 2015
I cannot seem to find the syntax to combine IN + CASE in a WHERE clause
WHERE
ses.BK_MS_SESSION <= '2015-03'
AND vis.CAT_DRAW_STATUS =
(CASE ses.BK_MS_SESSION
WHEN '2015-03' THEN vis.CAT_DRAW_STATUS
ELSE
CASE stat.BK_MS_VISIT_STATUS
WHEN 'T' THEN 'X'
ELSE vis.CAT_DRAW_STATUS
END
END
) IN ('D','R')
View 7 Replies
ADVERTISEMENT
Nov 6, 2015
I have a scenario where the End User is going to select two parameters. @AgentID and @Location If the End User selects @AgentID parameter, in my WHERE clause, I do not want to check the location condition. By default, the agent knows their location already.
If the End User select @Location parameter, in my WHERE clause, I still want to check the Agent condition.
@AgentID parameter would populate either with "All" or their actual agent# (76754 for example).
@Location parameter would populate either with "All" or their actual location (Birmingham or Bessemer for example)Sample of my current WHERE clause:
WHERE
gl.ReceiptDate >= @BeginDate and gl.ReceiptDate < DATEADD(D,1,@EndDate)
AND gl.AgentId = CASE WHEN @AgentID = 'All' THEN gl.AgentID ELSE @AgentID END
AND gl.Location = @Location
View 9 Replies
View Related
Jun 4, 2015
I have used the below update query. However, its updating only the first value. Like its updating AB with volume when c.Type = ABC, similarly for CD. Its not updating based on the 2nd or the next case condition.
Update XYZ Set AB = a.Amt * (CASE WHEN c.Type = 'ABC' THEN (c.volume)
WHEN c.TYPE = 'DEF' THEN (c.volume)
WHEN c.Type = 'GHI' THEN (c.volume)
Else 0
END),
CD = CASE WHEN c.Type = 'MARGIN' THEN '4105.31'
WHEN c.Type = 'ABC' THEN '123.1'
WHEN c.Type = 'DEF' THEN '234.2'
WHEN c.Type = 'GHI' THEN '567.1'
END
from table1 a join table2 b
on a.Cust = b.Customer
join table3 c
on b.account = c.account and b.channel =c.channel
Why its not working properly? But if i use Select statement instead of update query its working properly.
View 18 Replies
View Related
Sep 24, 2015
For Below example when @x=1 to retrieve col>0 rows or all rows.
With out another if else blocks or Dynamic sql to solve only in where clause.
select 0 col into #x
union
select 1 col
union
select 2 col
declare @x INT =1
SELECT * FROM #x
where col>CASE WHEN @x=1 THEN 0 ELSE (col=col) END
--here in case i want to compare only when @x=1 then col>0 other wise select all rows with out filter
View 5 Replies
View Related
Nov 16, 2015
I have scenario where i have to pick one particular value from where condition. Here is the example:A store can have different types i-e A or B , A and B or either A or B.
Store Type Sales
11 A 1000
23 A 1980
23 B 50
5 B 560
I want to filter the store in "where clause" where
1)- if the store has type A and B, then assign only A
2)- if the store has type A associated with it then assign A
3)- if the store has type B associated with it, then assign B.
Select Store, sum(sales), Type
from table1
where (TYPE]= (case when [TYPE] in ('A','B') then 'A'
when [TYPE]='A' then 'A' else 'B'end))
GROUP BY [store], [TYPE]
The above statement is not working for when store has only Type B associated with it.
View 7 Replies
View Related
May 8, 2015
I would like to be able to combine the functionality of IN and LIKE in a WHERE clause. Although the simple AdventureWorks2012 example below illustrates the concept with 3 search criteria, the real-world example I need to apply the concept to has a couple dozen. This returns 50 rows, but requires multiple OR ... LIKE functions:
SELECT DISTINCT c.Name
FROM Sales.Store c
WHERE c.Name LIKE '% sports %'
OR c.Name LIKE '% exercise %'
OR c.Name LIKE '%toy%'
What I would like to do is something like this, which doesn't work:
SELECT DISTINCT c.Name
FROM Sales.Store c
WHERE c.Name IN(LIKE '% sports %', LIKE '% exercise %', LIKE '%toy%')
I could load up a cursor and loop through it, but the syntax is more cumbersome than the multiple LIKE statements, not to mention most SQL programmers are horrified at the mention of the abominable word 'cursor' for performance reasons.
View 7 Replies
View Related
Apr 3, 2008
I have two queries that I'm trying to combine, but can't figure out how to combine them ... successfully!?! The first query is pretty simple in that I'm looking at several fields from two different tables, no big deal.
The second query calculates the years, months, days between two dates that are used in the first query. I'm stumped on how to combine the queries so that they place nice with each other and return results.
Here's the first query ...
select
RTRIM(RTRIM(vpi.LastName) + ', ' + RTRIM(ISNULL(vpi.FirstName,''))) Employee,
convert(varchar,vpi.FromEffectiveDate,101) PositionStart,
convert(varchar,vpi.ToEffectiveDate,101) PositionChange,
convert(varchar,vpi.PositionStartDate,101) PositionStartDate,
vpi.PositionReason, vpi.PositionCode, vpc.PositionCodeDescription
from vhrl_positioninfo vpi
inner join position_codes vpc on vpi.PositionCode = vpc.PositionCode
Here's the second query ...
select
[Age] = convert(varchar, [Years]) + ' Years ' +
convert(varchar, [Months]) + ' Months ' +
convert(varchar, [Days]) + ' Days', *
from
(
select
[Years] = case when BirthDayThisYear <= Today
then datediff(year, BirthYearStart, CurrYearStart)
else datediff(year, BirthYearStart, CurrYearStart) - 1
end,
[Months]= case when BirthDayThisYear <= Today
then datediff(month, BirthDayThisYear, Today)
else datediff(month, BirthDayThisYear, Today) + 12
end,
[Days]= case when BirthDayThisMonth <= Today
then datediff(day, BirthDayThisMonth, Today)
else datediff(day, dateadd(month, -1, BirthDayThisMonth), Today)
end,
Birth = convert(varchar(10) ,Birth, 121),
Today = convert(varchar(10), Today, 121)
from
(
select BirthDayThisYear =
case when day(dateadd(year, datediff(year, BirthYearStart, CurrYearStart), Birth)) <> day(Birth)
then dateadd(day, 1, dateadd(year, datediff(year, BirthYearStart, CurrYearStart), Birth))
else dateadd(year, datediff(year, BirthYearStart, CurrYearStart), Birth)
end,
BirthDayThisMonth =
case when day(dateadd(month, datediff(month, BirthMonthStart, CurrMonthStart), Birth)) <> day(Birth)
then dateadd(day, 1, dateadd(month, datediff(month, BirthMonthStart, CurrMonthStart), Birth))
else dateadd(month, datediff(month, BirthMonthStart, CurrMonthStart), Birth)
end,
*
from
(
select BirthYearStart = dateadd(year, datediff(year, 0, Birth), 0),
CurrYearStart = dateadd(year, datediff(year, 0, Today), 0),
BirthMonthStart = dateadd(month, datediff(month, 0, Birth), 0),
CurrMonthStart = dateadd(month, datediff(month, 0, Today), 0),
*
from
(
select birth = convert(datetime, fromeffectivedate) ,
Today = case when convert(datetime, toeffectivedate) = '3000-01-01'
THEN convert(datetime, convert(int,getdate()))
else vpi.toeffectivedate
end
from vHRL_PositionInfo vpi inner join position_codes vpc
on vpi.PositionCode = vpc.PositionCode
) aaaa
) aaa
) aa
)a
Here's the sample data ...
vpi table ...
LastName FirstName FromEffectDate ToEffectDate PosStartDate PosReason PosCode
Doe John 2001-10-15 3000-01-01 10-15-2001 Transfer OperPack
Smith Tom 1994-11-28 2001-10-14 1994-11-28 New Hire OperDC
vpc table ...
PosCode PosDescription
OperPack Pack Line Operator
OperDC Descaler Operator
This is what the results should look like ...
John, Doe 2001-10-15 3000-01-01 10-15-2001 Transfer OperPack Pack Line Operator 6 Years 11 Months 16 Days
John, Doe 1994-11-28 2001-10-14 1994-11-28 New Hire OperDC Descaler Operator 6 Years 6 Months 19 Days
I know the date calculation piece adds 5 additional fields to the end, but they are not needed for the final report. Any help would be greatly appreciated! Thank you! Jena
View 5 Replies
View Related
Nov 4, 2015
I have a quite big SQL query which would be nice to be used using UNION betweern two Select and Where clauses. I noticed that if both Select clauses have Where part between UNION other is ignored. How can I prevent this?
I found a article in StackOverflow saying that if UNION has e.g. two Selects with Where conditions other one will not work. [URL] ....
I have installed SQL Server 2014 and I tried to use tricks mentioned in StackOverflow's article but couldn't succeeded.
Any example how to write two Selects with own Where clauses and those Selects are joined with UNION?
View 13 Replies
View Related
May 4, 2015
I have column with value of all upper case, for example, FIELD SERVICE, is there anyway, I can convert into Field Service?
View 7 Replies
View Related
Jul 6, 2015
I have 4 table
TBLA
id
1
2
3
----
TBLB
ID COUNT
1 2
2 2
3 2
----
TBLC
ID COUNT
1 2
2 2
----
TBLD
ID COUNT
1 3
2 3
NEED TO GET OUT PUT LIKE BELOW
ID aCOUNT bCOUNT cCOUNT dCOUNT
1 2
2 3
2 2
2 2
3 2
View 2 Replies
View Related
Jul 23, 2005
Is there a way to construct a query to select for whole words only?select id from bookdata where titles like '%Test%' gets everything withtest somewhere in the field. So you could get records which have testas a subset of a larger word like 'testing' etc...What I am interested in is finding just the individual words in astored field.Say a field has 'Test your knowledge on this one.' and you want to find'Test' or 'knowledge' the word, not test or knowledge as parts ofothers words etc...anywhere and everywhere in the field and involvingmany records . How can you do this? or can this be done?Thanks for any help.
View 5 Replies
View Related
Jun 17, 2003
Hi,
My database is case insensitive. However, the application is case sensitive for the data in the table.
I need to find out the data from the table where the data is stored in lower case.
Here is the sample data:
Table: inv_manager
column: sku varchar(5)
Data: 1134X
1135x
1123a
b145Y
I just need query to return row 2, 3, 4.
Here is my query:
select sku from inv_manager where sku like lower('%[a-z]%')
The problem is it returns all the rows from the table including first one.
How can I return just the data with lower case ?
Thanks
View 2 Replies
View Related
Aug 13, 2015
I have one table list this
declare @test table(Id int, Description varchar(500))
insert into @test
values (1, '<b>Name :</b> XUZ <br/><br/>'),
(1, '<b>Type : </b> QWE <br /><br/>'),
(2, '<b>Name : </b> ABC <br /><br/>'),
(2, '<b>Type : </b> FGH <br /><br/>')
My expected result is
1, '<b>Name :</b> XUZ <br/><br/> <b>Type : </b> QWE <br /><br/>'
2, '<b>Name : </b> ABC <br /><br/> <b>Type : </b> FGH <br /><br/>'
As you can see its combine two rows of data group by id. Issue is If I use for xml path('') then its replace my html tags <b> to like <b> so after that then I again i need to replace all these symbols. Is it possible to get expected result without using xml path or if we use xml path then still my html tag leave as it is.
View 5 Replies
View Related
Jun 12, 2015
How to combine two or more procedure to make a single query.
I tried like below:
EXEC PROC1
UNION
EXEC PROC2
UNION
EXEC PROC 3
Its throwing invalid syntax.
View 3 Replies
View Related
Oct 18, 2015
I have 2 tables, i need to take the max date from PAY and Combine in MEN
MEN
======
id | Fname
========
1 | AAA
2 | BBB
3 | CCC
PAY
===
id | Tdate
=========
1 | 01.01.2015
1 | 02.01.2015
1 | 03.01.2015
2 | 06.01.2015
3 | 09.01.2015
3 | 10.01.2015i
I need to show this:
id | Fname | Tdate
=============
1 | AAA | 03.01.2015
2 | BBB | 06.01.2015
3 | CCC | 10.01.2015
View 5 Replies
View Related
Sep 15, 2015
The below code returns a NULL for all the Differential backups. I am trying to return the word Differential when there is a NULL because I can tell from when the NULLs occur that those are my differential backups. How can I get the result I want?
SELECT
CONVERT(CHAR(100), SERVERPROPERTY('Servername')) AS Server,
msdb.dbo.backupset.database_name,
msdb.dbo.backupset.backup_start_date,
msdb.dbo.backupset.backup_finish_date,
CASE
WHEN msdb..backupset.type = 'D' THEN 'Database'
[Code] .....
View 9 Replies
View Related
Oct 15, 2015
I'd like to get results from ZTest_Contract being my result set, and would like to combine the subquery (which gets the Max) into the primary view ZTest_Contract.
CREATE VIEW [dbo].[ZTest_Contract] AS
Select
M.CUSTNMBR,
M.ADRSCode,
M.Contract_number,
M.MaxWSCONTSQ,
M.Equipment_id,
[Code] ......
View 3 Replies
View Related
Jul 16, 2015
I have the table below and like to combine the rows to create a single link row in a new column. The rows should be combined based on the job number columns which is the same for the rows to be combined.
DECLARE @M31
( M31_SQL_ID INT
,JOB_NUMBER INT
,LINE_NUMBER INT
,WORKS_DESC VARCHAR)
[Code] ...
Output should be as below
219242
16/7/15 called tenant and she thought we would just fix for free - advised her I can get a quote how ever she may have to pay - she will call back
219245
16/7/15 called tnt said no report number. Said she will speak with her husband and call back with her decision and 16/07/15 the work order was sent to agent ...
View 3 Replies
View Related
Jul 1, 2015
I need a query to publish the front page of a blog. Each blog post needs to show BlogTitle, BlogText, PublishDate, PublishBy, Primary Image and number of comments. I would like to be able to do this in one sql statement, if possible.
The table structure is below, you can assume the first image returned from the image table is the primary image.
CREATE TABLE [dbo].[Blogs](
[ID] [int] IDENTITY(1,1) NOT NULL,
[BlogTitle] [nvarchar](200) NULL,
[BlogText] [nvarchar](max) NULL,
[Tags] [nvarchar](200) NULL,
[Code] ....
View 3 Replies
View Related
Nov 19, 2015
I am wanting to create a query so that I can combine each of the found duplicates into one entry.
An example of this is:
Name |ID |Tag |Address |carNum
-------------------------------------------------------
Bob Barker |2054| 52377 |235 Some road |9874
Bill Gates |5630| 69471 |014 Washington Rd. |3700
Bob Barker |2054| 97011 |235 Some road |9874
Bob Barker |2054| 40019 |235 Some road |9874
Steve Jobs |8501| 73051 |100 Infinity St. |4901
John Doe |7149| 86740 |7105 Bull Rd. |9282
Bill Gates |5630| 55970 |014 Washington Rd. |3700
Tim Boons |6370| 60701 |852 Mnt. Creek Rd. |7059
In the example above, Bob Barker and Bill gates are both in the database more than once so I would like the output to be the following:
Bob Barker |2054|52377/97011/40019|235 Some road |9874
Bill Gates |5630|69471/55970 |014 Washington Rd.|3700
Steve Jobs |8501|73051 |100 Infinity St. |4901
John Doe |7149|86740 |7105 Bull Rd. |9282
Tim Boons |6370|60701 |852 Mnt. Creek Rd. |7059
Notice how Bob Barker & Bill Gates appends the tag row (the duplicated data) into one row instead of having multiple rows. This is because I do not want to have to check the previous ID and see if it matches the current id and append to the data.
View 2 Replies
View Related
Jan 4, 2002
This is a CASE statement that I am using in the WHERE clause of my query.
SQL Syntax checker keeps returning an error (Incorrect syntax near '=').
Can anyone help me figure out what I need to do to get this to work?
Case When (@Weekday=-1 and @Saturday=0 and @Sunday=0) Then (L1.[Weekday]=-1 AND L2.[Weekday]=-1 AND L3.[Weekday]=-1 AND L4.[Weekday]=-1)
When (@Weekday=0 and @Saturday=-1 and @Sunday=0) Then (L1.Saturday=-1 AND L2.Saturday=-1 AND L3.Saturday=-1 AND L4.Saturday=-1)
When (@Weekday=0 and @Saturday=0 and @Sunday=-1) Then (L1.Sunday=-1 AND L2.Sunday=-1 AND L3.Sunday=-1 AND L4.Sunday=-1)
When (@Weekday=-1 and @Saturday=-1 and @Sunday=-0) Then (L1.Sunday=0 AND L2.Sunday=0 AND L3.Sunday=0 AND L4.Sunday=0)
When (@Weekday=-1 and @Saturday=0 and @Sunday=-1) Then (L1.Saturday=0 AND L2.Saturday=0 AND L3.Saturday=0 AND L4.Saturday=0)
When (@Weekday=0 and @Saturday=-1 and @Sunday=-1) Then (L1.[Weekday]=0 AND L2.[Weekday]=0 AND L3.[Weekday]=0 AND L4.[Weekday]=0)
Else
((L1.[Weekday]=-1 AND L2.[Weekday]=-1 AND L3.[Weekday]=-1 AND L4.[Weekday]=-1) OR
(L1.Saturday=-1 AND L2.Saturday=-1 AND L3.Saturday=-1 AND L4.Saturday=-1) OR
(L1.Sunday=-1 AND L2.Sunday=-1 AND L3.Sunday=-1 AND L4.Sunday=-1))
End
View 3 Replies
View Related
Jan 28, 2004
I am stumped trying to use case/if type conditions in having clause. Not sure if it's possible or my syntax or both.
Trying to do something like this:
CASE WHEN (dbo.t_COT_Summary.TCD >= dbo.ReportDate(CONVERT(nvarchar(30), GETDATE(), 101))) THEN
HAVING dbo.t_COT_AP_Exclude.Primary_ID IS NOT NULL
ELSE
HAVING dbo.t_COT_AP_Exclude.Primary_ID IS NULL
END
dbo.t_COT_Summary.TCD = Target Completion Date
dbo.ReportDate = Previous Business Day Function
dbo.t_COT_AP_Exclude.Primary_ID = A left joined ID value I wish to exclude or include in the main query's having.
I hope this makes sense... any suggestions on a better way to do this would be greatly appreciated!
View 2 Replies
View Related
Aug 23, 2007
A deveoper just asked me if there is a way to use a case in a where clause. Is this feasible or will we have to do some dynamic sql
where (cr.cb_routine = 1 or cr.cb_urgent = 1 or cr.cb_emergency_room = 1
or cr.cb_on_site_clinic = 1 or cr.cb_retro_request = 1 or cr.cb_initial = 1
or cr.cb_followup = 1 or cr.cb_in_person = 1 or cr.cb_telemed = 1
or cr.df_within is not null or cr.df_provider is not null
or cr.df_proc_test_spec is not null or cr.df_provider_area is not null)
and p.privacy_level = 10
and pe.Location_ID = @Location and
case when @status = 'Pended' then cr.cb_supp_info_need1 = 1
case when @status = 'Criteria for service not met' then cr.cb_criteria_not_1 = 1
case when @status = 'Other' then cr.cb_other_1 = 1
case when @status = 'All' then
View 1 Replies
View Related
Apr 19, 2007
Code:
WHERE
weekdayname(weekday(sfa_admin_sbaccount.add_time)) =
case
when "Monday"
then (((SFA_ADMIN_SBACCOUNT.ADD_TIME)>=Date()-3 And (SFA_ADMIN_SBACCOUNT.ADD_TIME)<Date()))
else (((SFA_ADMIN_SBACCOUNT.ADD_TIME)>=Date()-1 And (SFA_ADMIN_SBACCOUNT.ADD_TIME)<Date())));
end
This keeps telling me I'm missing an operator. What I want the query to do is to evaluate the current day's date, then use that to determine whether it needs to set a WHERE clause that goes back 3 days (if it's a Monday) or one day (if it's not a Monday)
This is in Access. Any suggestions?
View 4 Replies
View Related
Dec 15, 2004
Dear all...
need your help... i am now trying to create a report using SQL reporting services... when declare all the @parameters needed in where clause, i have come across a problem. where one of the parameters that prompting user to key in...i need to put in some condition.
select..................(blah blah)......
......(SELECT CASE WHEN
((SELECT COUNT(*)
FROM tbl_OutpatientReg OPT
WHERE OPT.PatientID = tbl_Patient.PatientID)) = 1 THEN 0 ELSE 1 END) AS PTType ............................(blah blah).......
where (CONVERT(Varchar(10), tbl_OutpatientReg.VisitDatetime, 103) BETWEEN @FromDate AND @ToDate) OR (@FromDate = ' ') OR (@ToDate = ' ')
AND (@PatientType = CASE WHEN
(SELECT COUNT(*)
FROM tbl_OutpatientReg OPT
WHERE OPT.PatientID = tbl_Patient.PatientID) = 1 THEN 0 ELSE 1 END)
my situition is something like above, i know i have done something wrong in teh WHERE clause for the @PatientType.... can i ask how to restrict the parameters entered by user, let's say if user enter parameter "0", then the visitcount is 1, if enter "1" then the visit count refers to more than 1...
thanks in advanced ...................
View 2 Replies
View Related
Feb 5, 2015
i Have the following SQL Statement
Select * from dtree
WHERE Subtype=848 AND
(MODIFYDATE between to_date(%2,'dd/mon/yyyy HH24:MI:SS') AND to_date(%3,'dd/mon/yyyy HH24:MI:SS') )
the numnbers %1, %2, %3 are variables and they get the values from another application. It works so far, but there case I can't handle.If the date values (%2,%3) are empty.I want that my query finds everything without considering the Date condition..I tried it with a CASE condition:
Select * from dtree
WHERE Subtype=848 AND
AND
(MODIFYDATE between to_date(CASE LEN(%2)=0 THEN '03/Feb/2015 00:00:00' END,'dd/mon/yyyy HH24:MI:SS') AND to_date(CASE LEN(%3)=0 THEN '05/Feb/2015 00:00:00' END,'dd/mon/yyyy HH24:MI:SS') )
but it doesn't work. How I can handle empty values?
View 1 Replies
View Related
Jun 13, 2007
is this correct?(where clause only)
where budget = case when price > 2.0 then 'True' else 'False' end
Funnyfrog
View 7 Replies
View Related
Feb 29, 2008
hello,
Can anybody see why this is failing at line 19
incorrect syntax near =
?
declare @Date datetime
declare @type int
declare @isnew int
declare @isreturn int
declare @isold int
SET @Date = '2008-03-04'
SET @type = 1
SET @isnew=1
SELECT [date],
SUM(amount) as s_amount
FROM values
WHERE convert(char(10),[date],23) = @Date
AND status > 0 AND
CASE WHEN @isnew=1 THEN
(loan.isnew=1)
WHEN @isreturn=1 THEN
((loan.isreturn=1) and loan.isold=0)
WHEN @isold=1 THEN
loan.isold=1
END
AND type = @type
GROUP BY [date]
kind regards,
jamie
View 6 Replies
View Related
Jan 23, 2006
I am attempting to write a stored procedure that will accept a column name in the form of an nvarchar parameter along with a corresponding value to use to filter the returned results. Obviously I can write a CASE statement with the query repeated for each case with the applicable WHERE clause, but after some research I did find that according to some sites, using the CASE statement in the WHERE clause is perfectly legal. However, I have tried the following code, which is basically a cut & paste version of what I found described, but SQL Server keeps generating errors at the first WHEN clause. I would appreciate anyone's guidance getting this right.
SELECT *
FROM tblTest
WHERE CASE @FilterKey
WHEN 'Description' THEN [Description]=@FilterValue
WHEN 'UpdateTime' THEN [UpdateTime]=@FilterValue
END
In this case, the table [tblTest] has two columns: [Description] and [UpdateTime] and the parameters @FilterKey and @FilterValue would be defined in the sproc definition - or inline with DECLARE/SET statements in Query Analyzer.
Keep in mind that the goal is to NOT have a separate parameter for each property so the (@p is null OR p=@p) method is not appropriate.
Oh, I have also tried to bring the CASE condition inline with the WHEN clause, for instance, WHEN @FilterKey='Description' THEN..., with no change in the results.
Thanks in advance for the feedback.
View 4 Replies
View Related
Jan 22, 2007
I need a SQL statement that selects a specific year (@yr type int) in the "createddate" column...if this @yr is equal to 0 then I want to select ALL columns regardless of the year...This is what I have so far, but it doesnt work...SELECT * FROM tblUsersWHERE year(CreatedDate)=CASEWHEN @yr<>'0' THEN @yrELSE NOT NULLEND
View 1 Replies
View Related
Oct 3, 2007
Hi!I want to make search engine and I have problem with query for this search. User can write username to search or text to search or both. So at first I made query for each event individually: ALTER PROCEDURE [dbo].[Show_Search_Topics]
@username varchar(200),
@search_text varchar(200),
@days int
AS
DECLARE @date DATETIME
SET @date = DATEADD(day,@days,GETDATE())
IF @username IS NOT NULL AND @search_text IS NULL
BEGIN
SELECT COUNT(dbo.forum_topics.post_user_id) AS UserPosts, forum_topics_1.post_title, dbo.aspnet_Users.UserName, forum_topics_1.post_id,
forum_topics_1.post_current_date, forum_topics_1.post_stick, forum_topics_1.post_user_id, forum_topics_1.post_cat_id,
dbo.forum_kategorie.forum_kat_kolor, dbo.forum_kategorie.forum_kat_nazwa, COUNT(DISTINCT forum_topics_2.post_id) + 1 AS post_total
FROM dbo.forum_topics INNER JOIN
dbo.aspnet_Users ON dbo.forum_topics.post_user_id = dbo.aspnet_Users.uID INNER JOIN
dbo.forum_topics AS forum_topics_1 ON dbo.aspnet_Users.uID = forum_topics_1.post_user_id INNER JOIN
dbo.forum_kategorie ON forum_topics_1.post_cat_id = dbo.forum_kategorie.forum_kat_id LEFT OUTER JOIN
dbo.forum_topics AS forum_topics_2 ON forum_topics_1.post_id = forum_topics_2.post_parrent_id
GROUP BY forum_topics_1.post_title, dbo.aspnet_Users.UserName, forum_topics_1.post_parrent_id, forum_topics_1.post_id, forum_topics_1.post_current_date,
forum_topics_1.post_stick, forum_topics_1.post_user_id, forum_topics_1.post_cat_id, dbo.forum_kategorie.forum_kat_kolor,
dbo.forum_kategorie.forum_kat_nazwa
HAVING (forum_topics_1.post_parrent_id = 0) AND (dbo.aspnet_Users.UserName = @username) AND (forum_topics_1.post_current_date >= @date)
ORDER BY forum_topics_1.post_stick DESC, forum_topics_1.post_current_date DESC
END
ELSE
IF @username IS NULL AND @search_text IS NOT NULL
BEGIN
SELECT COUNT(dbo.forum_topics.post_user_id) AS UserPosts, forum_topics_1.post_title, dbo.aspnet_Users.UserName, forum_topics_1.post_id,
forum_topics_1.post_current_date, forum_topics_1.post_stick, forum_topics_1.post_user_id, forum_topics_1.post_cat_id,
dbo.forum_kategorie.forum_kat_kolor, dbo.forum_kategorie.forum_kat_nazwa, COUNT(DISTINCT forum_topics_2.post_id) + 1 AS post_total
FROM dbo.forum_topics INNER JOIN
dbo.aspnet_Users ON dbo.forum_topics.post_user_id = dbo.aspnet_Users.uID INNER JOIN
dbo.forum_topics AS forum_topics_1 ON dbo.aspnet_Users.uID = forum_topics_1.post_user_id INNER JOIN
dbo.forum_kategorie ON forum_topics_1.post_cat_id = dbo.forum_kategorie.forum_kat_id LEFT OUTER JOIN
dbo.forum_topics AS forum_topics_2 ON forum_topics_1.post_id = forum_topics_2.post_parrent_id
GROUP BY forum_topics_1.post_title, dbo.aspnet_Users.UserName, forum_topics_1.post_parrent_id, forum_topics_1.post_id, forum_topics_1.post_current_date,
forum_topics_1.post_stick, forum_topics_1.post_user_id, forum_topics_1.post_cat_id, dbo.forum_kategorie.forum_kat_kolor,
dbo.forum_kategorie.forum_kat_nazwa
HAVING (forum_topics_1.post_parrent_id = 0) AND (forum_topics_1.post_current_date >= @date) AND (forum_topics_1.post_title LIKE '%' + @search_text + '%')
ORDER BY forum_topics_1.post_stick DESC, forum_topics_1.post_current_date DESC
END
ELSE
IF @username IS NOT NULL AND @search_text IS NOT NULL
BEGIN
SELECT COUNT(dbo.forum_topics.post_user_id) AS UserPosts, forum_topics_1.post_title, dbo.aspnet_Users.UserName, forum_topics_1.post_id,
forum_topics_1.post_current_date, forum_topics_1.post_stick, forum_topics_1.post_user_id, forum_topics_1.post_cat_id,
dbo.forum_kategorie.forum_kat_kolor, dbo.forum_kategorie.forum_kat_nazwa, COUNT(DISTINCT forum_topics_2.post_id) + 1 AS post_total
FROM dbo.forum_topics INNER JOIN
dbo.aspnet_Users ON dbo.forum_topics.post_user_id = dbo.aspnet_Users.uID INNER JOIN
dbo.forum_topics AS forum_topics_1 ON dbo.aspnet_Users.uID = forum_topics_1.post_user_id INNER JOIN
dbo.forum_kategorie ON forum_topics_1.post_cat_id = dbo.forum_kategorie.forum_kat_id LEFT OUTER JOIN
dbo.forum_topics AS forum_topics_2 ON forum_topics_1.post_id = forum_topics_2.post_parrent_id
GROUP BY forum_topics_1.post_title, dbo.aspnet_Users.UserName, forum_topics_1.post_parrent_id, forum_topics_1.post_id, forum_topics_1.post_current_date,
forum_topics_1.post_stick, forum_topics_1.post_user_id, forum_topics_1.post_cat_id, dbo.forum_kategorie.forum_kat_kolor,
dbo.forum_kategorie.forum_kat_nazwa
HAVING (forum_topics_1.post_parrent_id = 0) AND (forum_topics_1.post_current_date >= @date) AND (forum_topics_1.post_title LIKE '%' + @search_text + '%') AND
(dbo.aspnet_Users.UserName = @username)
ORDER BY forum_topics_1.post_stick DESC, forum_topics_1.post_current_date DESC
END
RETURN This 3 queries are different only by Having clause. So I want to put If/Case in Having clause, but I have problem. Can anyone help me?Also I want to make paging from SQL level, so if anyone will be so helpful and make working this query with this: ALTER PROCEDURE [dbo].[Show_Search_Topics]
@username varchar(200),
@search_text varchar(200),
@days int,
@page int,
@page_size int
AS
WITH Results As
(
//QUERY)
)
SELECT * FROM Results
WHERE RowNumber BETWEEN (@page_size * @page + 1) AND (@page_size * (@page + 1))
ORDER BY forum_topics_1.post_stick DESC, forum_topics_1.post_current_date DESC
RETURN I will be grateful :-)
View 5 Replies
View Related
Feb 21, 2008
Hi,
I need help to use CASE Statement within my WHERE Clause. I want to change the WHERE Clause based on my condition as following:
SELECT ...
FROM ...
WHERE (condition)
AND (condition)
AND (condition)
AND (
CASE Table.Category
WHEN 'Drinks' THEN
Table1.Field1 = 1 -- Problem line
ELSE
Table1.Field1 = 1 AND Table1.Field2 = 1 -- Problem line
END
)
In the above case, my WHERE Clause is dependent on one of the fields in a table. If it has a certain value then only Table1.Field1 is used otherwise Table1.Field1 & Field2 come into action.
I am getting error on the mentioned line (Problem Line). Since CASE is an expression and does not execute a statement, can anyone help me to get my WHERE Clause working...
Thanks in advance...
View 3 Replies
View Related
Feb 29, 2008
For Example:SELECT Column1, Column2
FROM Table
WHERE
Column1 = (
SELECT CASE @Test4Nulls
WHEN 1 THEN NULL
ELSE Column1 END) Basically, I want to test for Nulls in a column if my variable @Test4Nulls is True, however, I never get any results back. I believe it is because I am Criteria = NULL instead of Criteria IS NULL, however, I cannot use IS in a case statement How do I test for nulls in a case statement
View 3 Replies
View Related