I have the following code:
SqlCommand command = new SqlCommand(
@"DECLARE @month int, @year int, @dateToCheck datetime;
SET @month = @month;
SET @year = @year;
SET @dateToCheck = dateadd(month, 1, datefromparts(@year, @month, 1))
SELECT p.name, dtc.cost_price, p.date_created
FROM [dbo].[Company_Local_Invoice_] claidig
JOIN Type_Company dtc on claidig.ID = dtc.id
WHERE p.date_created < @dateToCheck
AND (p.date_left is null or p.date_left >= @dateToCheck)", conn);
command.Parameters.Add("@month", SqlDbType.Int).Value = month;
command.Parameters.Add("@year", SqlDbType.Int).Value = year;
The problem is that I can't seem to pass my SET parameters using command.Parameter.Add() .
The error that I get is:
The variable name '@month' has already been declared. Variable names must be unique within a query batch or stored procedure.
Why is this and how can I work around this?
DECLAREanything when you make a query like that from ADO.Net. Just take out theDECLAREs andSETs and just add theParameters.dateToCheckfrom the query, my query will fail (or return bad results)... >= @dateToCheck...with... >= dateadd(month, 1, datefromparts(@year, @month, 1))...