Link to home
Start Free TrialLog in
Avatar of johnkainn
johnkainn

asked on

Select all or just one

I have a table Table1 (Id, TText)
I have a parameter @Id.  If @Id is null I would like to return all rows, otherwise the row where Table.Id=@Id. How is best to do this?
Avatar of Umar Topia
Umar Topia
Flag of India image

if @id is null
begin
    select * from table1
else
   select * from table1 where id = @id
end
ASKER CERTIFIED SOLUTION
Avatar of Pratima
Pratima
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You could check out sommarskog.se on Dynamic Search Conditions in T-SQL.
It takes about an hour to read, but it is worth it, IMHO.

Or you could just do something like this

if @ID is null begin
   select * from Table1
end
else begin
   select * from Table1 where table1.id=@ID
end

or
select * from Table1 where table1.id=@ID or @ID is null

But only if your table is small! Bigger tables will take too long.

Best regards,
Henrik
I meant
if @id is null
    select * from table1
else
   select * from table1 where id = @id

Open in new window