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?
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?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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
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
begin
select * from table1
else
select * from table1 where id = @id
end