这是我的存储过程
CREATE PROCEDURE Test_SP
@from int,
@to int,
@year int,
@office varchar(MAX),
@fund varchar(MAX)
AS
SELECT
AccntTbl.Id,
AccntTbl.accnt,
ISNULL(SupplyTbl.Supply, 0) AS Supply,
AccntTbl.office,
AccntTbl.exp,
AccntTbl.dateCreated
FROM AccntTbl
LEFT OUTER JOIN
(SELECT idAccnt,
SUM(amount) AS Supply
FROM SuppyTbl AS SupplyTbl1
WHERE (MONTH(dateCreated) BETWEEN @from AND @to) AND
(YEAR(dateCreated) = @year) AND fund = @fund
GROUP BY idAccnt) AS SupplyTbl
WHERE YEAR(AccntTbl.dateCreated) = @year AND
AccntTbl.office = @office AND
AccntTbl.fund = @fund
GROUP BY AccntTbl.Id,
AccntTbl.accnt,
AccntTbl.appro,
Supply.Supply
这里从VB.NET调用
conn.Open()
Dim cmd As New SqlCommand("Test_SP", conn)
With cmd
.CommandType = CommandType.StoredProcedure
.Parameters.Add("@from", SqlDbType.VarChar).Value = Int32.Parse(TextBox1.Text)
.Parameters.Add("@to", SqlDbType.VarChar).Value = Int32.Parse(TextBox2.Text)
.Parameters.Add("@year", SqlDbType.VarChar).Value = Int32.Parse(YearLbl.Text)
.Parameters.Add("@office", SqlDbType.VarChar).Value = Dashboard.OfficeTxt.Text
.Parameters.Add("@fund", SqlDbType.VarChar).Value = FundLbl.Text
End With
我如何才能在TEST_SP
中检索其中的某些字段,就像我只想要AccntTbl.Accnt
和ISNULL(SupplyTbl.Supply, 0) as supply
这是我已经做过的示例代码
Dim cmd As New SqlCommand("Select AccntTbl.Accnt, ISNULL(SupplyTbl.Supply, 0) as supply from Test_SP", conn)
我知道它错了,它说'找不到存储过程' ...大声笑,很高兴得到任何帮助:)
答案 0 :(得分:0)
一种方法是使用user defined table valued function:
CREATE FUNCTION [dbo].[Test_SP]
( @from int,
@to int,
@year int,
@office varchar(MAX),
@fund varchar(MAX)
)
RETURNS TABLE
AS
RETURN (
SELECT AccntTbl.Id,
AccntTbl.accnt,
ISNULL(SupplyTbl.Supply, 0) AS Supply,
AccntTbl.office,
AccntTbl.exp,
AccntTbl.dateCreated
FROM AccntTbl
LEFT JOIN
(SELECT idAccnt,
SUM(amount) AS Supply
FROM SuppyTbl AS SupplyTbl1
WHERE MONTH(dateCreated) BETWEEN @from AND @to
AND YEAR(dateCreated) = @year
AND fund = @fund
GROUP BY idAccnt) AS SupplyTbl
WHERE YEAR(AccntTbl.dateCreated) = @year
AND AccntTbl.office = @office
AND AccntTbl.fund = @fund
GROUP BY AccntTbl.Id,
AccntTbl.accnt,
AccntTbl.appro,
Supply.Supply
);
查询:
SELECT Accnt, Supply
FROM [dbo].[Test_SP](1, 12, 2015, 'Baltimore', 'aaa');
请注意,条件YEAR(dateCreated) = @year
和MONTH(dateCreated)
为nonSARGable,因此如果dateCreated
列上有索引,则查询优化程序会跳过它。