all groups > sql server programming > august 2006 >
You're in the

sql server programming

group:

Need an IF statement in a query


Need an IF statement in a query Jeff Griffin
8/5/2006 7:50:02 PM
sql server programming: Basically I need an If statement in a query. I am working on website for my
Wife (She is a teacher) and she will be posting spelling words to this
particular page. She wants the parents to be able to either see all words or
only the words for a particular week.

I have modified the club site starter package to suit her needs and have
modified the page where it listed people to list spelling words. It has a
control at the top with a button for show all and individual buttons
corresponding to each school week to sort the words by. The database has a
field for the Word and one for the week.

I can use a WHERE statement when using the week control to sort the words by
school week but when I click show all it shows me nothing (presumibly
because I am passing it nothing and thus nothing matches). I think what I
need is some sort of Query somilar to the psuedo code below:

If Week == "" SELECT ID, Words, Week FROM WordWall ELSE SELECT ID, Words,
Week WHERE Week=@week FROM WordWall

Is this possible? Does anyone have any other ideas? The webiste in question
is www.mrsgriffin.com if it helps.

--
Jeff Griffin
Windows XP Media Center Edition MVP
www.thegreenbutton.com
Re: Need an IF statement in a query Kalen Delaney
8/5/2006 8:06:43 PM
You can use an IF in a query, but it is unclear where your control week is
coming from. Is it the variable @week that you have in the WHERE clause? You
cannot refer to a column from a table in isolation like that, but you can
refer to a variable, if it has already been set. Also, the FROM comes before
the WHERE

But maybe something like this will work instead:

SELECT ID, Words, Week
FROM WordWall
WHERE Week=@week OR @week = ''

So if @week is empty, all rows will be true, but if @week is not empty, only
weeks equal to @week will be true.

(note you should use single quotes and not double, and the '' is two single
quotes)
--
HTH
Kalen Delaney, SQL Server MVP


[quoted text, click to view]

Re: Need an IF statement in a query Jeff Griffin
8/5/2006 8:57:02 PM
@week is a string value representing the number of the school week, i.e 1, 2,
3 etc.

Here is an example of the type of data that needs to be displayed:

ID Word Week

1 Apple 1
2 Boat 1
3 Cherry 2
..
..
..
87 Tree 24


Basically the ID is not displayed and the week is not displayed but she
needs the parents to be able to click 24 for instance and Tree will be the
only thing displayed.

I tried what you said but it still does not work. I have uploaded a ziped
version of the aspx file and stored procedure that it references if that
would help to see what I am trying to do. The zip file is at
www.jeffreygriffin.com/downloads/wordwall.zip

Thanks!

--
Jeff Griffin
Windows XP Media Center Edition MVP
www.thegreenbutton.com
www.jeffreygriffin.com


[quoted text, click to view]
Re: Need an IF statement in a query Jeff Griffin
8/5/2006 9:00:02 PM
Yeah, I gave that a try using some examples I had found googling for an
answer but could not get it to work, probibly I am not formatting something
correctly.


--
Jeff Griffin
Windows XP Media Center Edition MVP
www.thegreenbutton.com
www.jeffreygriffin.com


[quoted text, click to view]
Re: Need an IF statement in a query Kalen Delaney
8/5/2006 9:04:54 PM
What does 'does not work' mean?

Does a simple query looking for one value work?

SELECT ID, Words, Week
FROM WordWall
WHERE Week=@week

If the above works, it probably means that the 'empty' value in @week is not
really empty. In particular, if it realy is a number, it cannot be an empty
string. You need to figure out what is really in there if nothing is input
by the application.

Maybe try this:

SELECT ID, Words, Week
FROM WordWall
WHERE Week=@week or @week is NULL
--
HTH
Kalen Delaney, SQL Server MVP


[quoted text, click to view]

Re: Need an IF statement in a query Omnibuzz
8/5/2006 9:44:02 PM
Hi Jeff,
Maybe your input variable is null..
try this... very similar to what Kalen suggested..

SELECT ID, Words, Week
FROM WordWall
WHERE Week= @week OR coalesce(@week,'') = ''

Hope this helps
--
-Omnibuzz (The SQL GC)

http://omnibuzz-sql.blogspot.com/

Re: Need an IF statement in a query Jeff Griffin
8/5/2006 9:58:01 PM
You are correct, the input variable @week is null when you click show all.
When a user clicks show all I need it to show all records but it is not doing
so because it tries to filter the records against a null snd the field it is
quering against is never null, it will always contain a number.

I have tried your suggestion as well as Kalen's and both produce the same
bahavior as without the OR... Clicking a week will supply the words
corresponding to that week but clicking show all will produce nothing. Hope
this helps to explain.

--
Jeff Griffin
Windows XP Media Center Edition MVP
www.thegreenbutton.com
www.jeffreygriffin.com


[quoted text, click to view]
Re: Need an IF statement in a query Omnibuzz
8/5/2006 10:06:01 PM
Can you paste the SP that you have.. I am not able to access the link that
you gave...

And also see...from this query
SELECT ID, Words, Week
FROM WordWall
WHERE Week= @week OR coalesce(@week,'') = ''

I am using

coalesce(@week,'')

and not

coalesce(week,'')

Why do I have the doubt that you are trying the latter :)

And anyways.. try it this way if the week is numeric (of course I assume you
don't have a week with value 0 in the table)

SELECT ID, Words, Week
FROM WordWall
WHERE Week= @week OR coalesce(@week,0) = 0

--
-Omnibuzz (The SQL GC)

http://omnibuzz-sql.blogspot.com/
Re: Need an IF statement in a query Jeff Griffin
8/5/2006 10:25:01 PM
Stored Procedure to figure out the weeks and only display each week once:

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: <Author,,Name>
-- Create date: <Create Date,,>
-- Description: <Description,,>
-- =============================================
ALTER PROCEDURE [dbo].[WordsByLetter]

AS
DECLARE @number int, @index int, @max int
CREATE TABLE #results ( number int, num INT)
SET @index=1
SET @max=52

WHILE @index <= @max
BEGIN
SET @number = @index
INSERT INTO #results Select number=@number, num=count(*) from WordWall
where Week=@number
SET @index = @index + 1
END
Select * FROM #results
RETURN


The full page code (including your last suggestion):

<script runat="server">

protected void hp1_Click(object sender, System.EventArgs e)
{
Filter = ((LinkButton)sender).Text;
SqlDataSource2.SelectParameters[0].DefaultValue = Filter;
}

string Filter
{
get
{
object o = ViewState["Filter"];
return (o != null) ? (string)o : string.Empty;
}
set
{
ViewState["Filter"] = value;
}
}

string linkClass(string number)
{
if (number == Filter)
{
return "selectedLetter";
}
else
{
return "";
}
}

protected void showall_Click(object sender, System.EventArgs e)
{
Filter = "";
SqlDataSource2.SelectParameters[0].DefaultValue = Filter;
}

public string PreFormat(string content)
{
if (content != null)
{
return content.Replace("\r\n", "<br/>");
}
else
{
return null;
}
}

private bool IsAdmin;

protected void Page_Load(object sender, System.EventArgs e)
{
IsAdmin = User.IsInRole("Administrators");
panel1.Visible = IsAdmin;
}
</script>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1"
runat="Server">
<div id="body">
<Club:LoginBanner ID="LoginBanner1" runat="server" />
<!--

Left column

-->
<div id="columnleft">
<a name="content_start" id="content_start"></a>
<div class="leftblock">
<h2>
Word Wall</h2>
<p>
The purpose of this word wall is to keep you informed of
the spelling words that
your child is held accountable for. We call these the
"no excuses" words. They are
always up in the classroom, and now at home as well. I
hope that you will find this
helpful to you when working with your child. The word
wall will be updated on a
weekly bases as new words are added.</p>
</div>
</div>
<!--

Right column

-->
<div id="columnright">
<div class="rightblock">
<asp:Panel ID="panel1" runat="server"
CssClass="actionbuttons">
<Club:RolloverLink ID="RemoveBtn" runat="server"
Text="Add new Word" NavigateURL="WordWall_Edit.aspx?Action=New" />
</asp:Panel>
<div class="dashedline">
</div>
<div class="newscrumbs">
<asp:LinkButton ID="showall" runat="server" Text="Show
All" OnClick="showall_Click" />
<asp:SqlDataSource ConnectionString="<%$
ConnectionStrings:ClubSiteDB %>" ID="SqlDataSource1"
runat="server" SelectCommand="WordsByLetter"
SelectCommandType="StoredProcedure"/>
<asp:Repeater DataSourceID="SqlDataSource1"
ID="Repeater1" runat="server">
<ItemTemplate>
<asp:LinkButton ID="hp1" runat="server"
Text='<%#Convert.ToString(Eval("number"))%>' Visible='<%#
Convert.ToInt32(Eval("num")) > 0 %>'
OnClick="hp1_Click" CssClass='<%#
linkClass(Convert.ToString(Eval("number")))%>' />

</ItemTemplate>
</asp:Repeater>
</div>
<div class="dashedline">
</div>

<asp:SqlDataSource ID="SqlDataSource2" runat="server"
ConnectionString="<%$ ConnectionStrings:ClubSiteDB %>"
ProviderName="<%$ ConnectionStrings:ClubSiteDB.ProviderName
%>"
SelectCommand="SELECT Week, ID, Words FROM WordWall WHERE
Week=@filter OR coalesce(@filter,0) = 0 ORDER BY Words ASC">
<SelectParameters>
<asp:Parameter DefaultValue="" Name="filter"
Type="String" />
</SelectParameters>
</asp:SqlDataSource>

<br />

<asp:DataList ID="DataList1" runat="server"
DataSourceID="SqlDataSource2" HorizontalAlign="Center" RepeatColumns="1"
RepeatDirection="Vertical">
<ItemTemplate>
<asp:Panel ID="panel2" runat="server"
Visible='<%#IsAdmin %>'>
<Club:RolloverLink ID="EditBtn"
runat="server" Text="Edit" NavigateURL='<%#
"WordWall_Edit.aspx?Action=Edit&ArticleID=" + Convert.ToString( Eval("ID"))
%>' />
<Club:RolloverLink ID="RemoveBtn"
runat="server" Text="Remove" NavigateURL='<%#
"WordWall_Edit.aspx?Action=Remove&ArticleID=" + Convert.ToString( Eval("ID"))
%>' />
</asp:Panel>
<h1>
<asp:Label ID="WordsList" runat="server"
Font-Bold="true" Text= <%# (string) Eval("words") %>/>
</h1>
</div>
</ItemTemplate>
</asp:DataList>
</div>
</div>
<div class="clear2column">
</div>
</div>
</asp:Content>


--
Jeff Griffin
Windows XP Media Center Edition MVP
www.thegreenbutton.com
www.jeffreygriffin.com


[quoted text, click to view]
Re: Need an IF statement in a query Omnibuzz
8/5/2006 10:50:01 PM
Hi Jeff,
can't the first stored procedure be written this way..

ALTER PROCEDURE [dbo].[WordsByLetter]
AS
Select week as number,count(*) as num from WordWall
where week <=52
group by week

And You aren't using a stored procedure for the functionality you metioned


Can't you create a proc like this.. and call it the from the front end?

CREATE PROCEDURE [dbo].[GetWordsForWeek]
@filter int
AS
SELECT Week, ID, Words FROM WordWall WHERE
Week=@filter OR coalesce(@filter,0) = 0 ORDER BY Words ASC


--
-Omnibuzz (The SQL GC)

http://omnibuzz-sql.blogspot.com/

Re: Need an IF statement in a query Man-wai Chang
8/6/2006 12:00:00 AM
[quoted text, click to view]

Did you check out the CASE ... WHEN ... THEN ... END construct?

--
.~. Might, Courage, Vision, SINCERITY. http://www.linux-sxs.org
/ v \ Simplicity is Beauty! May the Force and Farce be with you!
/( _ )\ (Ubuntu 6.06) Linux 2.6.17.6
^ ^ 11:44:01 up 20 days 19:07 0 users load average: 1.00 1.00 1.01
Re: Need an IF statement in a query Jeff Griffin
8/6/2006 10:16:01 AM
Unfortunately that did not work either. I have got it working though, I think
the problem may have been sending a null for show all so I changed it to send
a wild negative number. Here is what I did in a stored procedure to make it
work in case it helps someone:


ALTER PROCEDURE [dbo].[GetWordsForWeek]
@filter int
AS
If @filter = -124456
SELECT Week, ID, Words FROM WordWall Order BY Words ASC
ELSE
SELECT Week, ID, Words FROM WordWall
Where Week = @filter
Order BY Words ASC


--
Jeff Griffin
Windows XP Media Center Edition MVP
www.thegreenbutton.com
www.jeffreygriffin.com


[quoted text, click to view]
Re: Need an IF statement in a query Omnibuzz
8/6/2006 7:38:01 PM
Jeff,
Good that you figured it out... I was using 0 to select all records
instead of -124456 that you used.. Anyways.. I thought 0 will be a valid
default value for week number :)

And just to wrap it up.. This will work too...

SELECT Week, ID, Words FROM WordWall
Where Week = @filter or @filter = -124456
Order BY Words ASC

Re: Need an IF statement in a query Tracy McKibben
8/7/2006 8:29:16 AM
[quoted text, click to view]


Your problem is here:
protected void showall_Click(object sender, System.EventArgs e)
{
Filter = "";
SqlDataSource2.SelectParameters[0].DefaultValue = Filter;
}

AddThis Social Bookmark Button