I'm searching for the cleanest solution here. I would like to code a stored procedure that should retrieve one record if the proper key is passed in input, or all the records if it is called without parameter.
Table FOO has two fields, CODE and DESCRIPTION. In Sql server 2008, i usually create a stored procedure with like this:
CREATE PROCEDURE getFoo
@CODE CHAR(3)=NULL
AS
IF @CODE is NULL
BEGIN
SELECT CODE,DESCRIPTION FROM FOO
END
ELSE
BEGIN
SELECT CODE,DESCRIPTION FROM FOO WHERE CODE=@CODE
END
GO
The main problem with my solution is obviously the repetition of the SELECT that could be painful if table has many fields or has many joins to other tables.
Another approach that i see in others SP is:
CREATE PROCEDURE getFoo
@CODE CHAR(3)=NULL
AS
DECLARE @FILTER CHAR(3)
SET NOCOUNT ON
IF @CODE is NULL SET @Filtro='%'
ELSE SET @FILTER =@CODE
SELECT CODE,DESCRIPTION
FROM FOO
WHERE
CODE like @FILTER
GO
What is your preferred code for this simple task? Do you construct it dinamically and use EXECUTE at the end? thanks