函数显示SQL Server存储过程中的单个返回值

本文关键字:过程中 单个 返回值 存储过程 存储 显示 SQL Server 函数 | 更新日期: 2023-09-27 18:28:21

我有一个不带参数的SQL Server存储过程。它通过数据库找到最常见的记录屏幕分辨率,并将所述分辨率作为唯一的返回值输出。

存储过程采用两列ScreenWidthScreenHeight(均为int),并将它们与其间的x连接,以返回屏幕分辨率的单个文本值

以下是存储过程:

ALTER PROCEDURE [dbo].[uspRetMostCommonScreenRes]
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    -- Insert statements for procedure here
    SELECT TOP 1 
        CAST(ScreenWidth as nvarchar(MAX)) + 'x' +
        CAST(ScreenHeight as nvarchar(MAX)) AS Resolutions
    FROM 
        BrowserInfoes
    GROUP BY 
        CAST(ScreenWidth as nvarchar(MAX)) + 'x' + CAST(ScreenHeight as nvarchar(MAX))
    ORDER BY 
        COUNT(*) DESC   
END

这执行得非常好,并返回值1600x1024

然后我想在C#中创建一些代码,这些代码将获得这个唯一值并将其存储到字符串值中。

我在C#和SQL Server之间的接口方面唯一的经验是通过实体框架输入数据,所以我不知道如何完成这项任务。

函数显示SQL Server存储过程中的单个返回值

您尝试执行的伪代码是以下

using(SqlConnection cnn = new SqlConnection(....here the connection string ....))
using(SqlCommand cmd = new SqlCommand("uspRetMostCommonScreenRes", cnn))
{
    cnn.Open();
    cmd.CommandType = CommandType.StoredProcedure;
    string result = cmd.ExecuteScalar().ToString();
}

此代码需要一个允许C#程序连接到数据库的连接字符串。然后定义一个指向存储过程和连接的SqlCommand
最后,您可以打开连接,将命令文本标记为StoredProcedure名称,并执行ExecuteScalar方法。

using语句负责关闭和处理连接以及命令

我建议更新proc,将两个INT值作为不同的值返回,这使您可以灵活地将它们分离或组合为"widthXheight"格式,或者两者兼而有之。

返回原始INT值的效率会高得多,因为GROUP BY的性能会降低,而GROUP BY必须对连接的值执行。

使用INT值而不是串联还可以将在(ScreenWidth、ScreenHeight)上创建的索引用于GROUP BY操作,这将进一步加快查询速度。

CREATE PROCEDURE [dbo].[uspRetMostCommonScreenRes]
(
  @Width INT OUTPUT,
  @Height INT OUTPUT
)
AS
SET NOCOUNT ON;
SELECT TOP 1 @Width = ScreenWidth,
             @Height = ScreenHeight
FROM BrowserInfoes
GROUP BY ScreenWidth, ScreenHeight
ORDER BY COUNT(*) DESC;

以下是如何使用它:

int _Height = -1;
int _Width = -1;
SqlConnection _Connection = new SqlConnection("connect string");
SqlCommand _Command = new SqlCommand("uspRetMostCommonScreenRes", _Connection);
_Command.CommandType = CommandType.StoredProcedure;
_SqlParameter _WidthParam = new SqlParameter("@Width", SqlDbType.Int);
_WidthParam.Direction = ParameterDirection.Output;
_Command.Parameters.Add(_WidthParam);
_SqlParameter _HeightParam = new SqlParameter("@Height", SqlDbType.Int);
_HeightParam.Direction = ParameterDirection.Output;
_Command.Parameters.Add(_HeightParam);
try
{
  _Connection.Open();
  _Command.ExecuteNonQuery();
  _Width = (int)_WidthParam.Value;
  _Height = (int)_HeightParam.Value;
}
finally
{
  _Connection.Close();
}