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?
johnkainnAsked:
Who is Participating?
 
Pratima PharandeConnect With a Mentor Commented:
Select * from tablename
where @id is Null OR Table.Id=@Id
0
 
Umar Topia.Net Full Stack DeveloperCommented:
if @id is null
begin
    select * from table1
else
   select * from table1 where id = @id
end
0
 
hspoulsenCommented:
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
0
 
Umar Topia.Net Full Stack DeveloperCommented:
I meant
if @id is null
    select * from table1
else
   select * from table1 where id = @id

Open in new window

0
All Courses

From novice to tech pro — start learning today.