dni*_*sml 5 c# sql stored-procedures rowcount executenonquery
我有各种存储过程。我需要一个存储过程来执行一个存储过程,然后仅返回行数(被调用过程返回的行数),并且需要用c#代码接收它。
最好的方法是什么?
情况:我有各种从c#代码调用的存储过程。现在出于另一个目的,我需要知道某个过程返回的行数(我不希望返回的行,我只需要行数)。我无法更改存储过程本身,因为我的许多C#代码都在使用它们,因此如果更改存储过程,事情可能会中断。这就是为什么我锁定一个过程,该过程将接受输入并(动态地)执行一个过程并返回行数,而不返回结果或行数。
我可以采取存储过程字符串并像执行
EXEC ('StoredProcedure @Keyword = ''' + @Key + '''')
Run Code Online (Sandbox Code Playgroud)
我在每个可能返回的行中都有一个ID作为列。我可以存储ID并对其进行计数,但是我不知道这是否是最好的主意。
我的数据库很大。我可以在c#中使用executenonquery(),但是当我用它执行任何存储过程时,它都返回-1。最好的方法是什么。谢谢。
假设您正在使用 SQL Server(从代码片段中可以看出),也许这样的东西适合您:
exec('exec <your stored procedure goes here>; select @@RowCount')
Run Code Online (Sandbox Code Playgroud)
由于您正在运行 SQL Server,我可以想到一种不一定很好的解决方案。
创建临时表(如果您有较新版本的 SQL Server,则为表变量)。然后执行:
exec(`
declare @t table (
<columns go here>
);
insert into @t
exec(''<your exec here>'');
select @rowcount
');
Run Code Online (Sandbox Code Playgroud)
既然我已经这么说了,我会推荐sp_executesql。事情是这样的:
declare @sql nvarchar(max) = N'exec '+@YOURQUERY + '; set @RowCount = @@RowCount';
exec sp_executesql @sql, N'@RowCount int output', @RowCount = RowCount output;
Run Code Online (Sandbox Code Playgroud)
昨天我花了大部分时间调试一个神秘的情况,当您在插入中调用存储过程时会出现该情况。