[英]SQL Server stored procedure only returns last row of temporary table
几周前,我使用的所有代码都达到了预期的目的,尽管我认为我无意中删除了一些东西,现在它不能正常工作。 存储过程假定返回多行数据,每行TopicID
、 TopicName
和PercentComplete
列。
在 JSONController / API 中,数据应该连接成一个单数字符串,其中每列用#
分隔,每行用|
分隔 .
例子:
"4#Ideology#50|5#Morality#100|6#Religion#0"
我现在注意到的是存储过程只返回最后一行,所以在这个例子中是“6#Religion#0”。
我错过了代码,还是我做错了什么? 同样在 JSONController/API 中,如何根据从存储过程返回的行数进行连接?
存储过程代码:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[getTopicsForSubject]
@SubjectID int,
@StudentID int
AS
BEGIN
CREATE TABLE #SubjectTopics
(
TopicID int,
Topic varchar(1000),
PercentComplete int
)
INSERT INTO #SubjectTopics
SELECT TopicID, topic, 0
FROM topic
WHERE SubjectID = @SubjectID
UPDATE #SubjectTopics
SET PercentComplete = ISNULL((SELECT PercentComplete FROM StudentTopic
WHERE topicid = #SubjectTopics.TopicID
AND StudentID = @StudentID), 0)
SELECT * FROM #SubjectTopics
RETURN
DROP TABLE #SubjectTopics
END
API / JSON Controller 代码:
private static string ExecuteSPGetSubjectsData(string queryString, string subjectID, string studentID)
{
string json = "";
string connectionString = ConfigurationManager.AppSettings["dbconn"].ToString();
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
// 1. create a command object identifying the stored procedure
SqlCommand cmd = new SqlCommand(queryString, conn);
// 2. set the command object so it knows to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;
// 3. add parameter to command, which will be passed to the stored procedure
cmd.Parameters.Add(new SqlParameter("@SubjectID", subjectID));
cmd.Parameters.Add(new SqlParameter("@StudentID", studentID));
// execute the command
using (SqlDataReader rdr = cmd.ExecuteReader())
{
// iterate over the results, printing each to console
while (rdr.Read())
{
json = (string)rdr[0].ToString() + "#" + (string)rdr[1].ToString() + "#" + (string)rdr[2].ToString() + "|";
}
}
}
return json;
}
您将需要 append(+=,而不仅仅是 =)每条记录的值到您的“json”变量 - 目前,您的代码行正在替换“json”变量值,因为它循环遍历每条记录(这解释了为什么最后结果具有最后一条记录的值)
while (rdr.Read())
{
json += (string)rdr[0].ToString() + "#" + (string)rdr[1].ToString() + "#" + (string)rdr[2].ToString() + "|";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.