C# 如果结果为多列,如何使用SqlCommand.ExecuteReader重构包含循环?
我在VisualStudio2019中收到S1751警告“重构包含循环以返回多个值” 当我使用ExecuteScalar返回单列的值时,会出现一些情况,但在本例中,我需要返回一行四列C# 如果结果为多列,如何使用SqlCommand.ExecuteReader重构包含循环?,c#,sql-server,C#,Sql Server,我在VisualStudio2019中收到S1751警告“重构包含循环以返回多个值” 当我使用ExecuteScalar返回单列的值时,会出现一些情况,但在本例中,我需要返回一行四列 sqlCommand sqlCommand = new SqlCommand(); sqlCommand.CommandText = "SELECT Total_Retirement_Need, Total_Social_Security,
sqlCommand sqlCommand = new SqlCommand();
sqlCommand.CommandText = "SELECT Total_Retirement_Need, Total_Social_Security, Total_Account_Income, Savings_And_Checking " +
"FROM tblA A INNER JOIN " +
"tblB B ON A.SessionId = B.SessionID " +
"WHERE A.SessionID = @sessionId " +
"AND B.Age = JSON_VALUE(formData, '$.goalData.clientARetireAgeText')";
sqlCommand.Parameters.Add("@sessionId", SqlDbType.NChar).Value = sessionId;
sqlCommand.Connection = conn;
conn.Open();
SqlDataReader reader = sqlCommand.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
decimal Total_Retirement_Needed = reader.GetDecimal(0);
decimal Total_Social_Security = reader.GetDecimal(1);
decimal Total_Account_Income = reader.GetDecimal(2);
decimal Savings_And_Checking = reader.GetDecimal(3);
return ("$" + Total_Retirement_Needed.ToString("N0"),
"$" + Total_Social_Security.ToString("N0"),
"$" + Total_Account_Income.ToString("N0"),
"$" + Savings_And_Checking.ToString("N0")
);
}
}
reader.Close();
return ("N/A", "N/A", "N/A", "N/A");
我不能使用ExecuteScalar,ExecuteReader给了我警告。我可以让它成为一个存储过程,如果这是“a”答案,我会接受它,但要寻找选项
谢谢 删除
而循环,不需要它,只需尝试读取即可。如果读取成功,则只需读取第一条记录
SqlDataReader reader = sqlCommand.ExecuteReader();
if (reader.Read())
{
decimal Total_Retirement_Needed = reader.GetDecimal(0);
decimal Total_Social_Security = reader.GetDecimal(1);
decimal Total_Account_Income = reader.GetDecimal(2);
decimal Savings_And_Checking = reader.GetDecimal(3);
return ("$" + Total_Retirement_Needed.ToString("N0"),
"$" + Total_Social_Security.ToString("N0"),
"$" + Total_Account_Income.ToString("N0"),
"$" + Savings_And_Checking.ToString("N0")
);
}
reader.Close();
您还应该使用TOPX
子句限制SQL查询结果。由于您只需要一条记录,因此无需返回多条记录
SELECT TOP 1 Total_Retirement_Need, Total_Social_Security, Total_Account_Income...
请尝试您希望查询返回多少行?一个?或者不止一行?查询只返回一行,然后警告[间接]告诉您只需要if
语句,因为由于返回
,它不能多次执行循环。此外,您还可以跳过HasRows
测试,因为reader.Read()
将返回false
如果HasRows
为false
。首先,将SQL查询设为返回单行,您可以通过where条件或在第二步中使用Top 1执行此操作,您可以将SqlDataAdapter与DataTable一起使用,以使用列名访问每个单元格