IF OBJECT_ID('procedurename','p') IS NOT NULL
DROP PROC procedurename
GO
CREATE PROCEDURE procedurename (
@topcount int,
@tsdate smalldatetime=NULL,
@latencytype char(2)=NULL,
@msgsource char(1)=NULL
)
AS
SET NOCOUNT ON
IF(@tsdate IS NULL)
BEGIN
--if the parm is passed null, just get the max value (should use idx effectively)
SELECT @tsdate = MAX(tsdate)FROM database.dbo.maintable
END
DECLARE @SQL VARCHAR(5000)
SET @SQL = 'SELECT TOP '+ CAST(@topcount AS VARCHAR)
' OrderNo,MsgSource,Latency,LatencyType,tsdate
FROM database.dbo.maintable WITH (NOLOCK)
WHERE tsdate >= CONVERT(datetime, '''+ CONVERT(varchar(10), @tsdate, 120) +''', 120 )
AND tsdate < DATEADD(day, 1, CONVERT(datetime, '''+ CONVERT(varchar(10), @tsdate, 120) +''', 120 ))
' + CASE WHEN @latencytype IS NULL THEN '' ELSE ' AND LatencyType = '''+@latencytype+''' ' END
+ CASE WHEN @msgsource IS NULL THEN '' ELSE ' AND MsgSource='''+@MsgSource+''' ' END
+ ' ORDER BY LatencyType,Latency DESC '
PRINT(@SQL)
--EXEC(@SQL)
GO
|