October 18, 2006 at 12:32 pm
I have had to modify some old stored procs written by a person who no longer works here and I have seen a few selects using '.... where 1=1 and column1 ....'
What does it do? It looks redundant but I'm not sure if this is something that speeds up searches or something.
Can anybody explain this to me?
October 18, 2006 at 12:46 pm
It will return all the rows in a table. I've seen it being used when "Depending upon condition certain where clause is applied"
October 18, 2006 at 12:57 pm
Thanks for your reply.
Right, it returns the whole table, but a select without a where clause does the same thing. So what is it then for? It doesn't make any sense to me.
October 18, 2006 at 1:00 pm
It makes the concatenation work easier. You don't have to check if a condition has been set before adding another conidtion dynamically. Query wise, that condition is checked once then ignored so speed is not affected.
October 19, 2006 at 10:28 am
Hi Ninja -
Could you please give an example? I'm not following how this makes concatenation work easier.
Thanks,
Susan
October 19, 2006 at 11:02 am
say i'm building a dynamic sql query
set @query = 'select * from table where 1=1 '
if @somecondition = 'yes'
begin
set @query = @query + ' and x=2'
end
exec @query
It makes the "and" a given instead of having to test for it. I don't use it much, but another programmer here uses it quite frequently.
October 19, 2006 at 11:07 am
Here is an example:
Create procedure ssp_findData
@i_UserID int = 0,
@i_DeptID int = 0
as
Begin
set nocount on
Declare @s_SQL varchar(512)
select @s_SQL = 'select * from UserDept where 1 = 1'
If @i_UserID <> 0
Begin
select @s_SQL = @s_SQL + ' and UserID = ' + Cast(@i_UserID as varchar(5))
End
If @i_DeptID <> 0
Begin
select @s_SQL = @s_SQL + ' and DeptID = ' + Cast(@i_DeptID as varchar(5))
End
select @s_SQL
set nocount off
End
I don't have to check to see if I need to put a "where" Clause or " and " etc. Hope this helps.
Thanks
Sreejith
October 19, 2006 at 11:08 am
What Dylan said .
I might add that this is most often used for "complex" search forms where any number of parameters can be entered.
October 19, 2006 at 11:09 am
Got it! Thanks for the explanation.
October 19, 2006 at 11:26 am
Thanks guys...
It actually is veru useful. I've created some sp with dynamic sql and have been dealing with that 'where used' problem....
It's a lot easier this way.
October 19, 2006 at 11:30 am
You might want to read this :
Viewing 11 posts - 1 through 10 (of 10 total)
You must be logged in to reply to this topic. Login to reply