I use the same logic on the front end using VB to SQL server which works fine, but never tried a stored procedure with the logic.
Can you please help me, construct a stored procedure.
User can choose any of the three(progno, projno, contractno) fields as a where condition.
I ma using asp.net as front end with sql server backend.
CREATE PROCEDURE dbo.USP_Searchrecords
(@.ProgNO nvarchar(50),
@.ProjNOnvarchar(50) ,
@.ContractNOnvarchar(50))
AS
DECLARE @.myselect nvarchar(2000)
DECLARE @.psql nvarchar(2000)
DECLARE @.strsql nvarchar(2000)
SET NOCOUNT ON@.psql = "SELECT * FROM Mytable"
IF @.ProgNO <> '' then
strsql = WHERE ProgNO = @.ProgNO
end ifIf @.ProjNO <> '' then
if strsql <> '' then
strsql = strsql & " and ProjNO =@.ProjNO
ELSE
strsql = wHERE ProjNO =@.ProjNO
END IF
END IFIf @.ContractNO <> '' then
if strsql <> '' then
strsql = strsql & " and ContractNO =@.ContractNO
ELSE
strsql = wHERE ContractNO =@.ContractNO
END IF
END IF@.myselect = @.psql + @.strsql
EXEC(@.myselect)
Please help. Thank you very much.CREATE PROCEDURE dbo.USP_Searchrecords
@.ProgNO nvarchar(50) = null,
@.ProjNOnvarchar(50) = null ,
@.ContractNOnvarchar(50) = null
AS
select * from mytable
where
(
((@.ProgNO is null) or (progNo = @.ProgNO))
AND
((@.ProjNO is null) or (ProjNo = @.ProjNO))
AND
((@.ContractNO is null) or (ContractNo = @.ContractNO))
)|||Do NOT do this.
::CREATE PROCEDURE dbo.USP_Searchrecords
should have a WITH RECOMPILE option here.
Problem is: Depending on the parameters you will get totally different access paths. Without indicating these should be evaluated EVERY TIME, the FIRST access path will be reused, EVEN if it is totally ridiculous given the exact parameters. This will result in awfully slow queries.|||>>should have a WITH RECOMPILE option here
Thona points out a great reason NOT to use Dynamic SQL if you dont have to.
Having an sp precompiled is one of the main performance benefits of using stored procedures - Unless you make changes to the table structure, introduce new indexes, or use Dynamic SQL you should'nt need to recompile your stored procedures.
No comments:
Post a Comment