Pat*_*ick 4 t-sql sql-server stored-procedures
I am working with Entity Framework in C# and am having an issue which I have tracked down to the SQL statement being generated.
The stored procedure takes in a table-valued parameter, but this doesn't seem to be the issue.
In SQL Profiler, I am seeing the following being executed:
declare @p3 dbo.PositiveTypes
insert into @p3 values(N'1')
insert into @p3 values(N'4')
insert into @p3 values(N'6')
exec sp_executesql N'dbo.SaveResults',
N'@resultID int, @positiveResults [PositiveTypes] READONLY',
@resultID=1,
@positiveResults=@p3
Run Code Online (Sandbox Code Playgroud)
This results in:
消息201,级别16,状态4,过程SaveResults,第0行
过程或函数'SaveResults'期望未提供参数'@resultID'。
此过程的定义是:
ALTER PROCEDURE [dbo].[SaveResults]
@resultID int,
@positiveResults AS dbo.PositiveTypes READONLY
Run Code Online (Sandbox Code Playgroud)
用户定义的类型为:
CREATE TYPE [dbo].[PositiveTypes] AS TABLE(
[TypeID] [tinyint] NULL
)
Run Code Online (Sandbox Code Playgroud)
这种sp_executesql语法有什么问题?为什么认为@resultID这里没有正确传递?
小智 6
我有同样的问题。
声明命令后,必须指定命令类型
SqlCommand cmd = new SqlCommand(@"sp_name", con);
cmd.CommandType = CommandType.StoredProcedure;
Run Code Online (Sandbox Code Playgroud)
如果您不这样做,.NET将会生成一个供使用的命令sp_executesql...,这就是...您如上所述指定命令类型并且所生成的代码正在使用的问题。
execute storedprocedure @param1 = ...
Run Code Online (Sandbox Code Playgroud)
您正在用来sp_executesql运行 SQL 文本dbo.SaveResults。dbo.SaveResults此 T-SQL 运行不带参数的过程。现在您明白该消息的来源了。该怎么办?使用EXEC:
EXEC dbo.SaveResults @resultID = 1234, @positiveResults = @p3
Run Code Online (Sandbox Code Playgroud)
或者,嵌套调用:
exec sp_executesql N'
EXEC dbo.SaveResults @resultID = @resultID, @positiveResults = @positiveResults
',N'@resultID int, @positiveResults [PositiveTypes] READONLY',@resultID=1,@positiveResults=@p3
Run Code Online (Sandbox Code Playgroud)
我缩进是为了更清楚。据我所知,第二个变体没有用。使用第一个。