无法在存储过程中加入tvp

时间:2015-09-07 13:53:09

标签: c# sql sql-server stored-procedures table-valued-parameters

当我从JOIN打电话给SP([dbo].[pr_2]任何一个表c#)时,我什么都没得到(我的DataReader包含0 rows )。但如果我在MSSMS中执行相同的SP,我就会得到我想要的东西。

我无法将表连接到tvp参数。

我的TVP

CREATE TYPE [dbo].[GuidList] AS TABLE(
    [Id] [uniqueidentifier] NOT NULL
)

存储过程[dbo].[pr_1] 这个SP的工作正常。我的结果是MSSMSC#

CREATE PROCEDURE [dbo].[pr_1]
  @tvp [dbo].[GuidList] READONLY
AS

BEGIN
    SELECT * 
    FROM @tvp
END

但是如果尝试加入任何数据(或表),我在C#中什么也得不到,但在MSSMS中,我得到了我想要的东西

存储过程[dbo].[pr_2]

CREATE PROCEDURE [dbo].[pr_2]
  @tvp [dbo].[GuidList] READONLY
AS

BEGIN
    SELECT 
        [id]
        ,[Name]
        ,[Email]
    FROM [dbo].[User] users
        inner join @tvp tvp on tvp.Id = users.UserId
    WHERE users.isActive = 1
END

我的c#代码

DataTable tvp = new DataTable();
tvp.TableName = "[dbo].[GuidList]";
tvp.Columns.Add("Id", typeof(Guid));

for (int i = 0; i < 10; i++)
{
    DataRow row = tvp.NewRow();
    //just for example
    row["Id"] = Guid.NewGuid();
    tvp.Rows.Add(row);
}

DataTable result = new DataTable();

using (SqlConnection connection = new SqlConnection("MyConStr"))
{
    using (SqlCommand command = new SqlCommand())
    {
        try
        {
            command.Connection = connection;
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "[dbo].[pr_2]";

            SqlParameter tvpSqlParam = new SqlParameter("@tvp", tvp);
            tvpSqlParam.SqlDbType = SqlDbType.Structured;
            tvpSqlParam.TypeName = "[dbo].[GuidList]";

            command.Parameters.Add(tvpSqlParam);

            connection.Open();

            using (SqlDataReader reader = command.ExecuteReader())
            {
                result.Load(reader);
            }

        }
        catch (SqlException sqlException)
        {
        }
        finally
        {
            command.Parameters.Clear();
        }
    }
}

我不知道那是什么。为什么我的SqlCommand只返回

declare @TVP [dbo].[GuidList]
insert into @TVP
SELECT [ContractTemplateId]
FROM [dbo].[MyTable]

exec [dbo].[pr_2] @tvp = @TVP

我想回来吗?

这是我的连接字符串

Data source=srv;Initial catalog=catcalog;Persist security info=True;User id=test;Password=pass;Connect Timeout=30;Max Pool Size=100;Connect Timeout=60;Failover Partner=SRV;

0 个答案:

没有答案