0

I have a SQL Query that I am trying to add to Powershell so that I can setup a routine to export a CSV file. The SQL works great:

declare @firstdayfilter datetime;
declare @lastdayfilter datetime;
declare @SalesDate  date;

set @firstdayfilter = (select DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) - 1, 0));
set @lastdayfilter = (SELECT DATEADD(DAY, -(DAY(GETDATE())), GETDATE()));
set @SalesDate = (select DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) - 1, 0));

select @firstdayfilter ,@lastdayfilter ,@SalesDate

When I move this into a Powershell file, I get an error when I try to declare the variable. I've tried many different iterations to no success. I am a noob at Powershell.

Here's what I had originally (for the first field).

$FirstDayFilter = @"
 Declare @firstdayfilter datetime ;
 set @firstdayfilter = (select DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) - 1, 0));
"@

$SqlQuery = @"
SELECT 
 $FirstDayFilter
"@

This is the error message I get:

Exception calling "Fill" with "1" argument(s): "Incorrect syntax near the keyword 
'Declare'."
At S:\Common\Active IT Projects\Projects\OrionSales\OrionCPIMTDSalesReport.ps1:277 char:5
+     $SqlAdapter.Fill($DataSet) #| Out-Null
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : SqlException

So what am I missing? I know other fields work. For example if I set $FirstDayFilter = "Test" it works.

1 Answer 1

3

This code:

$SqlQuery = @"
SELECT 
 $FirstDayFilter
"@

Produces this string:

SELECT 
Declare @firstdayfilter datetime ;
 set @firstdayfilter = (select DATEADD(mm, DATEDIFF(mm, 0, GETDATE()) - 1, 0));

...which is not valid SQL. Maybe you meant:

$SqlQuery = @"
 $FirstDayFilter
 SELECT @FirstDayFilter
"@
Sign up to request clarification or add additional context in comments.

1 Comment

That was my problem. Thank you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.