ADO.NET 在发送SQL语句到SQL Server数据库后,怎么知道真正INSERT,UPDATE,DELETE了多少行数据呢?
使用SQL Server内置的全局变量@@ROWCOUNT即可,@@ROWCOUNT可以返回在当前数据库连接(SqlConnection)中,执行的上一条SQL语句影响了多少行数据,使用示例如下所示:
INSERT INTO [dbo].[Person]([PersonCode],[Name],[Age],[City]) VALUES (N'P8000',N'Herry',50,N'Beijing') ,(N'P8001',N'Dan',50,N'Beijing') ,(N'P8002',N'Zen',52,N'Beijing') ,(N'P8003',N'Tim',52,N'Beijing') ,(N'P8004',N'Jhon',52,N'Beijing') SELECT @@ROWCOUNT--返回5 UPDATE [dbo].[Person] SET [PersonCode]=[PersonCode] SELECT @@ROWCOUNT--返回5 UPDATE [dbo].[Person] SET [PersonCode]=[PersonCode] WHERE [PersonCode] IN (N'P8003',N'P8004') SELECT @@ROWCOUNT--返回2 DELETE FROM [dbo].[Person] WHERE [PersonCode] IN (N'P8003',N'P8004',N'P8001') SELECT @@ROWCOUNT--返回3 DELETE FROM [dbo].[Person] WHERE 1<>1 SELECT @@ROWCOUNT--返回0 SELECT * FROM [dbo].[Person] SELECT @@ROWCOUNT--返回2
所以用ADO.NET执行INSERT,UPDATE,DELETE语句后,再使用查询SELECT @@ROWCOUNT查询出影响的行数返回给ADO.NET即可。不过要注意@@ROWCOUNT这个值要在INSERT/UPDATE/DELETE语句后立即获取,否则会被别的语句引响的行数代替,所以每次INSERT/UPDATE/DELETE后可以将它存入变量,等批处理结束后再RETURN