首页 > 解决方案 > 在 SQL 查询中传递 DECLARE 参数

问题描述

我有以下代码:

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;

问题是我似乎无法SET使用command.Parameter.Add().

我得到的错误是:

变量名“@month”已被声明。变量名称在查询批处理或存储过程中必须是唯一的。

为什么会这样,我该如何解决这个问题?

标签: c#sql-serverdatetime

解决方案


Gordon 的观点是,当您将参数传递给 sql 字符串时,它会在参数定义中添加“declare”语句。因此,您不需要对作为参数传入的任何内容进行声明。不过,您仍然需要声明从参数计算的任何变量。

var commandText = @"

  declare @dateToCheck datetime

  set @dateToCheck = dateadd(month, 1, datefromparts(@year, @month, 1))

  select 
    p.name, dtc.cost_price, p.date_created
  from 
    dbo.[Company_Local_Invoice_] claidig
    inner join 
    Type_Company dtc 
    on c
      laidig.ID = dtc.id 
  where
    p.date_created < @dateToCheck
    and 
    (
      p.date_left is null 
      or 
      p.date_left >= @dateToCheck
    )";

var command = new SqlCommand(commandText, conn);
command.Parameters.Add("@month", SqlDbType.Int).Value = month;
command.Parameters.Add("@year", SqlDbType.Int).Value = year;

推荐阅读