Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

Dynamic TSQL Statement with Dynamic Parameters

$
0
0

I'm trying to utilize a dynamic TSQL Statement where I can have various parameters passed of differing kinds, e.g. In some cases parameter 1 would be an int, other cases it may be a datetime, or varchar, etc.

I'm going to keep  a table of with certain key SQL Statements, and then parameters in another column so this can be resusable.

Here is my code:

Case 1



Declare @FromDate as DATE='2013-10-01'
Declare @ToDate as DATE='2013-10-31'
Declare @FamilyMember as nvarchar(2)='20'
DECLARE @retval int   
DECLARE @sSQL nvarchar(500);
DECLARE @ParmDefinition nvarchar(500);

DECLARE @tablename nvarchar(50)  

--Select Convert(nvarchar(15), @FromDate,126)

SELECT @sSQL = N'select count(distinct id) as AggregateCount from [Table] where familyMember = @FamilyMember 
and  DateStamp between @FromDate and @ToDate';



SET @ParmDefinition = N'@retvalOUT int OUTPUT';

EXEC sp_executesql @sSQL, @ParmDefinition, @retvalOUT=@retval OUTPUT;

Case 2

Declare @FromDate as DATE='2013-10-01'
Declare @ToDate as DATE='2013-10-31'
Declare @Id as int=3510021
DECLARE @retval int   
DECLARE @sSQL nvarchar(500);
DECLARE @ParmDefinition nvarchar(500);

DECLARE @tablename nvarchar(50)  

--Select Convert(nvarchar(15), @FromDate,126)

SELECT @sSQL = N'select count(distinct id) as AggregateCount from [Table] where Id=@Id
and  DateStamp between @FromDate and @ToDate';



SET @ParmDefinition = N'@retvalOUT int OUTPUT';

EXEC sp_executesql @sSQL, @ParmDefinition, @retvalOUT=@retval OUTPUT;


John


Viewing all articles
Browse latest Browse all 23857

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>