How NOT to Code - Example 8
So I mentioned that I would bounce around with languages a bit. Since many of us in the RIA development world do use Sql Server, I figure this would be nice to cover.
This is actually a fairly new one I learn at the local sql server user group. I actually would be surprised if anyone finds the problem in this one. This is really a dba level challenge, but it's good for programmers to know.
create procedure CustomerLookup
@CustomerID int = NULL
,@PersonID int = NULL
as
select * from Sales.Customer CU
inner join sales.salesorderheader sh on sh.customerid = cu.customerid
inner join sales.salesorderdetail sd on sd.salesorderID = sh.salesorderid
where (cu.customerid = @CustomerID or @CustomerID is NULL) and
(cu.personID = @PersonID or @PersonID is NULL)
Dave Ferguson wrote on 01/28/1010:47 AM
Nice one here. This is most definitely a DBA challenge but I'll take a stab anyways.First off.. the "select *" is a bad idea. Your queries should always only return the columns of data you need.
But, beyond that, it is a poorly constructed query. If I am reading this correctly the end result, if using default params of null, would return all rows where the joins succeed. I if the joins are a 1 to many you would end up with multiple rows for each customer. I am not a DBA so I don't know the precise reason why but I think it is because the where clauses cancel each other out.
--Dave