3

从 C#(.NET 4.5,Visual Studio 2013)调用 proc,它使用 sp_executesql 传递表变量。但是,SQL Server(在 2008 Std、2008 Ent 和 2012 Std 上测试)将其作为空表传递。

我希望这里的三个语句返回相同的结果,但最后一个没有。

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[_testproc]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[_testproc]
GO

IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'testType' AND ss.name = N'dbo')
DROP TYPE [dbo].[testType]
GO
--------------------------------
CREATE TYPE [dbo].[testType] AS TABLE(
    [ServerID] [int] NULL
    , [Field2] int NOT NULL
)

GO
---------------------------------
CREATE PROC _testproc
    @testTable testType READONLY 
AS

SELECT * FROM @testTable 

GO
---------------------------------
declare @x testtype

INSERT INTO @X values (1,2)
INSERT INTO @X values (3,4)

--Begin Three calls that should return the same result
--Query the table directly
SELECT * FROM @x

--Call it the way I would through t-sql
exec _testproc @testTable = @x

--Call it the way C# in Visual Studio 2013 calls it
exec sp_executesql N'dbo._testproc',N'@testTable [dbo].[TestType] READONLY',@testTable=@x

--Cleanup
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[_testproc]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[_testproc]
GO

IF  EXISTS (SELECT * FROM sys.types st JOIN sys.schemas ss ON st.schema_id = ss.schema_id WHERE st.name = N'testType' AND ss.name = N'dbo')
DROP TYPE [dbo].[testType]
GO

对我来说,显而易见的答案是不要在 proc 中将 sp_executesql 与表变量一起使用,但这段 C# 代码正是这样做的。

using (SqlCommand cmd = new SqlCommand("dbo._testproc", connCentral))
            {
                SqlParameter sqlpTestTable = cmd.Parameters.AddWithValue("@TestTable", dtTestTable);
                sqlpTestTable.SqlDbType = SqlDbType.Structured;
                sqlpTestTable.TypeName = "dbo.TestType";

                using (SqlDataAdapter aTest = new SqlDataAdapter())
                {
                    aTest.SelectCommand = cmd;

                    aTest.Fill(dsTest2, "Test2");
                }
            }

您能给我的任何帮助将不胜感激。谢谢!!!

4

1 回答 1

2

改变...

exec sp_executesql N'dbo._testproc',N'@testTable [dbo].[TestType] READONLY',@testTable=@x

到...

exec sp_executesql N'dbo._testproc @testTable',N'@testTable [dbo].[TestType] READONLY',@testTable=@x

我测试了它,它有效。您将变量传递给执行的命令文本,但您没有在命令文本中使用该变量。

于 2013-12-19T23:02:58.927 回答