首页 > 解决方案 > 如何从 C# 聊天机器人与机器人应用程序在 SQL Server 中执行存储过程?

问题描述

这是 SQL 查询:

CREATE PROCEDURE get_nearest_Restaurants
    @lat FLOAT,
    @lng FLOAT
AS
BEGIN
    DECLARE @point GEOMETRY

    SET @point = GEOMETRY::Point(@lat, @lng, 4326)

    SELECT TOP (5) 
        Id, Name, City, @point.STDistance(Location) AS Location 
    FROM 
        [dbo].[Restaurants]
    ORDER BY 
        @point.STDistance(Location)
END
GO

标签: c#sql-server

解决方案


您可以使用SqlCommand来引用您的StoredProcedure,然后使用 获取数据SqlDataAdapter

不要忘记传递参数SqlParameter

get_nearest_Restaurants此代码将在您的 BotApplication 中调用您的 sp ( ):

public async Task<DataTable> ExecuteSp(string lat, string lng)
{
    SqlConnection cnn = new SqlConnection("Data Source=ServerName/IP;Initial Catalog=DatabaseName;User ID=UserName;Password=Password");

    SqlCommand cmd = new SqlCommand();
    SqlDataAdapter da = new SqlDataAdapter();
    DataTable dt = new DataTable();
    try
    {
        cnn.Open();
        cmd = new SqlCommand("get_nearest_Restaurants", cnn);
        cmd.Parameters.Add(new SqlParameter("@lat", lat));
        cmd.Parameters.Add(new SqlParameter("@lng", lng));
        cmd.CommandType = CommandType.StoredProcedure;
        da.SelectCommand = cmd;
        await Task.FromResult(da.Fill(dt)); 
    }
    catch (Exception)
    {

    }
    finally
    {
        cnn.Close();
        cmd.Dispose();
    }
    return dt;
}

要连接到SQL-Server您应该使用SqlConnection. 中有一个属性SqlConnection,即ConnectionString,它定义了我们的位置SQL-Server以及我们如何连接到它。


推荐阅读