Thursday, May 5, 2016

EXEC Query

DECLARE @EndDate VARCHAR(10);
DECLARE @SQL VARCHAR(5000);
DECLARE @LastDate VARCHAR(10);
DECLARE @StartDate VARCHAR(10);
DECLARE @StartYear VARCHAR(4);
DECLARE @StartMonth VARCHAR(2);

SET @StartDate = CONVERT(VARCHAR(20),DATEADD(MONTH, DATEDIFF(MONTH, 0, GETDATE()) -1, 0),23);
SET @EndDate = CONVERT(VARCHAR(20),DATEADD(MONTH,1,@StartDate),23);
SET @LastDate = CONVERT(VARCHAR(20),DATEADD(Day,-1,@EndDate),23);
SET @StartYear = CONVERT(VARCHAR(4),datepart(yyyy,@StartDate));

SET @StartMonth = CONVERT(VARCHAR(2),datepart(mm,@StartDate));

Set @SQL 'Select *,date as ''Trans Date'' From DBYear'+ @StartYear  +'.dbo.Table WHERE TransDate BETWEEN '''+ @StartDate + ''' AND '''+ @EndDate + '''; 
exec(@SQL)
select(@SQL)

No comments:

Post a Comment