【发布时间】:2016-04-15 09:02:52
【问题描述】:
我的情况是我向存储过程发送查询以通过 c# 代码运行它。
这个查询是通过c#代码生成的,当我直接复制粘贴到storedprocedure上运行时它运行成功。
我的查询是这样的:
select acString from account_string where bstatus=1 and (dbo.getElementFromString(1,acstring) between 1000 and 4587)
(我通过调试运行我的代码后复制了它,因为它是动态生成的)。
我通过这样的参数发送到存储过程的相同查询:
ALTER PROCEDURE [dbo].[sp_shekharSheetDisplay]
@action varchar(50)='',
@query varchar(max)='' //here i send my query through parameter
AS
BEGIN
SET NOCOUNT ON;
BEGIN TRY
if(@action='sheet')
begin
select accountstring,
isnull(sum(case when amttype='dr' then (amount) end),'0.00') DR,
isnull(sum(case when amttype='cr' then (amount) end),'0.00') CR,
isnull(sum(case when amttype='dr' then (amount) end),'0.00')-isnull(sum(case when amttype='cr' then (amount) end),'0.00') amt
from tbltransaction_detail where accountstring in (@query)
group by accountstring
end
END TRY
BEGIN CATCH
EXECUTE sp_ErrorDB_AddNew
SELECT 3,'SQL Exception'
END CATCH
END
它在运行时不起作用。它不会向我的数据集发送任何数据(在下面的 ds 中):
Cls_budget objBudget = new Cls_budget();
DataSet ds = new DataSet();
objBudget.Action = "sheet";
objBudget.Query = query;
ds = objBudget.ManageSheet();// I found no data in ds here in my table
但是当我通过复制和替换下面一行中的@query 来静态尝试该查询时:
来自 tbltransaction_detail where accountstring in (@query)
然后我得到所有显示数据的表格(请参阅http://prntscr.com/ashf14)
为什么我使用@query 时它不起作用?
【问题讨论】:
-
人们似乎对 SQL 产生了一种神奇的信念,即不知何故,字符串会神奇地变成执行代码,或变成多个单独的值。它在 SQL 中不像那样工作。但令我惊讶的是,它在大多数其他主流语言中都不是这样工作的。如果您在 C# 中调用一个期望接收字符串的方法,并且将文字
"System.Environment.MachineName"传递给它,您希望该方法接收该文字字符串还是您的机器名称?现在看看你上面的SQL。您希望这两个中的哪一个发生在那里? 为什么? -
Parameterize an SQL IN clause 类似情况。
actual values!=string/subquery
标签: c# sql sql-server stored-procedures