0

我有这个存储过程:

ALTER PROCEDURE [dbo].[uspPages_HotelPrices_Lookup_Select] 
    @HotelCode nvarchar(100)
AS
BEGIN
    SET NOCOUNT ON;

    SELECT * 
    FROM tPages_HotelPrices_Lookup 
    WHERE HotelCode IN (SELECT * FROM DBO.ufSplit(@HotelCode, ',')) 
END

DBO.ufsplit拆分逗号分隔的字符串并返回一个表,其中每一行包含每个逗号分隔的值。

我使用以下代码将字符串传递给此存储过程:

static void Main(string[] args)
{
    HotelCodesTableAdapter hcTa = new HotelCodesTableAdapter();
    DestinationMarketingEntity.HotelCodesDataTable hotelCodesDt = hcTa.GetData();

    string hotelCodesString = "";
    //Comma separating hotel codes and putting each word in '' to be passed to sql sproc as a list
    for (int i = 0; i < hotelCodesDt.Count; i++)
    {
        hotelCodesString += hotelCodesDt.Rows[i].ItemArray.GetValue(0).ToString() + ",";
    }

    hotelCodesString = hotelCodesString.TrimEnd(',');

    HiltonEEHotelPricesTableAdapter hEETa = new HiltonEEHotelPricesTableAdapter();
    WorldWideFeedEntity.HiltonEEHotelPricesDataTable hEEDt= hEETa.GetData(hotelCodesString);
}

最后一行是调用存储过程的地方。

本质hotelCodesString上将类似于,"1,2,3"但这不会从这个存储过程中返回任何内容。但是,如果我运行以下命令:

select * 
from tPages_HotelPrices_Lookup 
  where HotelCode IN 
(
SELECT *
FROM DBO.ufSplit('1,2,3',',')
);

它可以取回我想要的一切。我在这里错过了什么吗?为什么在使用 c# 从值传递时它不会返回任何内容?

4

2 回答 2

3

根本不要进行拆分。创建一个表值参数并将其传递给您的存储过程。然后更改您的存储过程以加入表值参数。

您的 sproc 最终将如下所示:

CREATE PROCEDURE [dbo].[uspPages_HotelPrices_Lookup_Select] 
    @HotelCodes dbo.MyCodesTable READONLY
AS
BEGIN
    SET NOCOUNT ON;

    SELECT * 
    FROM tPages_HotelPrices_Lookup a 
    INNER JOIN @HotelCodes b ON (a.ID = b.ID)
END

在 SO 和互联网上有很多使用表值参数的好例子。习惯的好方法。

于 2013-11-04T16:41:29.057 回答
1

您可以尝试在 C# 中而不是在数据库级别进行拆分。

 string[] m_separators = new string[] { "," };
 string[] m_stringarray = somestring.Split(m_separators, StringSplitOptions.RemoveEmptyEntries);

或者按照关于将数组传递给存储过程的示例。无论如何,这可能是您想要做的。

于 2013-11-04T16:36:09.020 回答