c# - 在 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”已被声明。变量名称在查询批处理或存储过程中必须是唯一的。
为什么会这样,我该如何解决这个问题?
解决方案
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;
推荐阅读
- java - 处理许多客户端的最佳方式(使用线程?)
- c++ - 无法在 MacOS10.14 上安装 OpenGL
- google-apps-script - gs - 即使关闭工作表也可以运行脚本吗?
- php - PhpStorm 捕获它应该跳过的请求 (xdebug.remote_autostart=0)
- julia - 朱莉娅决策树模型 - 获取功能列表
- swift - 没有初始值的存储属性会阻止合成初始化程序
- c# - 如何从双向链表c#中打印每个列表中的素数(每行五个数字)
- c# - 使用 .net Core 删除表前缀
- r - 如何在函数中调用 S4 类 obj?
- mongodb - 在 API 级别禁用前夕 mongodb 上的分页