Reputation: 71
I created a query looking at some transaction information. The time period criteria is conditional - on the 5th of the month, it needs to look at days 16-last day of the previous month. On the 20th of the month, it needs to look at days 1-15 of the same month. It will run automatically. A fine gentleman or woman on Stack Overflow gave me the following stored procedure to use, which worked perfectly:
DECLARE @today SMALLDATETIME, @start SMALLDATETIME, @end SMALLDATETIME;
SET @today = DATEADD(DAY, 0, DATEDIFF(DAY, 0, CURRENT_TIMESTAMP));
SET @start = DATEADD(DAY, 1-DAY(@today), @today);
SET @end = DATEADD(DAY, 15, @start);
IF DATEPART(DAY, @today) <= 15
BEGIN
SET @start = DATEADD(MONTH, -1, @end);
SET @end = DATEADD(DAY, 1-DAY(@today), @today);
END
SELECT ... WHERE h.billed_date >= @start AND h.billed_date < @end;
Now they want this converted to a view that they can access from a 3rd party data integration tool. Google tells me views can't call stored procedures in SQL Server. Their DBA said the whole query could also be converted to a stored procedure. How do I convert a query into an SP so that it can be accessed by a data integration tool? Here's a simplified version of the query.
SELECT
c.customer_name
, cc.category_name
, h.acct_bal
FROM
customer c
inner join htransactions h on c.customer_id = h.customer_id
left outer join customer_category cc on cc.category_id = c.category_id
WHERE
h.billed date >= @start
AND h.billed date < @end
Thanks. I'm a business analyst trying to get better at SQL. My foundational querying SQL is getting stronger. I need to transistion to learning more about variables and stored procedures.
Upvotes: 0
Views: 844
Reputation: 280252
If this just needs to be a stored procedure, then:
CREATE PROCEDURE dbo.PullData -- whatever
AS
BEGIN
SET NOCOUNT ON;
DECLARE @today SMALLDATETIME, @start SMALLDATETIME, @end SMALLDATETIME;
SET @today = DATEADD(DAY, 0, DATEDIFF(DAY, 0, CURRENT_TIMESTAMP));
SET @start = DATEADD(DAY, 1-DAY(@today), @today);
SET @end = DATEADD(DAY, 15, @start);
IF DATEPART(DAY, @today) <= 15
BEGIN
SET @start = DATEADD(MONTH, -1, @end);
SET @end = DATEADD(DAY, 1-DAY(@today), @today);
END
SELECT ... WHERE h.billed_date >= @start AND h.billed_date < @end;
END
GO
Upvotes: 1