Sunday, 28 July 2013

How to make dynamic stored procedure .


How to make dynamic stored procedure .


-- =============================================
-- Author: <Author,,Omveer Singh>
-- Create date: <Create Date,29/06/2013,>
-- Description: <Description,tO SHOW COMMUNICATION HISTORY,>
-- Example : EXEC SP_GET_USER_INFO '1/Jan/2013','30/Dec/2013',1,'1'
-- =============================================
CREATE PROCEDURE [dbo].[SP_GET_USER_INFO]
(
@FromDate varchar(50),
@ToDate varchar(50),
@Status varchar(50),
@MemberType varchar(50)
)
AS

Declare @query varchar(8000)
Declare @Where varchar(8000)

BEGIN
SET @query='SELECT * FROM [USER] '
SET @Where=''


IF (ISNULL(@FromDate,'')<>'')
BEGIN
SET @Where=@Where+'[User].RegistrationDate'+'>='''+ @FromDate + Char(39)
END

IF (ISNULL(@ToDate,'')<>'')
BEGIN
IF (LEN(@Where)>1)
begin
SET @Where=@Where + ' AND [User].RegistrationDate<=' + Char(39) + @ToDate + Char(39)
end
Else
begin
SET @Where=@Where + '[dbo].[User].RegistrationDate<='+ Char(39) + @ToDate + Char(39)
END
END

IF (ISNULL(@Status,'')<>'')
BEGIN
IF (LEN(@Where)>1)
begin
SET @Where=@Where + ' AND [dbo].[User].Status='+@Status
END
else
begin
SET @Where=@Where + '[dbo].[User].Status='+@Status
end
END
IF (ISNULL(@MemberType,'')<>'')
BEGIN
IF (LEN(@Where)>1)
begin
SET @Where=@Where + ' AND [dbo].[User].UserTypeId='+@MemberType
END
else
begin
SET @Where=@Where + '[dbo].[User].UserTypeId='+@MemberType
end
END
IF(ISNULL(@Where,'')<>'')
BEGIN
SET @query=@query+ ' WHERE ' + @Where
--PRINT @query
END
EXEC (@query)
END
GO


0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home