将存储过程转换为查询 (SQL Server Compact)
本文关键字:SQL Server Compact 查询 存储过程 转换 | 更新日期: 2023-09-27 18:27:28
我正在尝试将以下存储过程转换为查询,以便我可以在SQL Server CE中使用它
USE TestResults
GO
CREATE PROCEDURE uspInsertNewTest
(@DeviceSerialNumber nvarchar(50),
@DeviceType nvarchar(50),
@ElapsedTime int)
AS
BEGIN
INSERT INTO [TestResults].[dbo].[Tests]([Date], [Device], [DeviceType], [ExecutionTimeMs])
OUTPUT INSERTED.TestId
VALUES (GETDATE(), @DeviceSerialNumber, @DeviceType, @ElapsedTime)
END
GO
从上面的脚本中,我只能理解它需要三个输入参数
- 设备序列号
- 设备类型
- 已用时间
但它会更新表中的 5 列Tests
包括 Date
和 TestId
。
由于我无法在 SQL Server CE 中使用存储过程,因此我已将上述脚本转换为字符串查询,
string queryString = "INSERT INTO Tests ([Date], [Device], [DeviceType], [ExecutionTimeMs]) VALUES (@Date, @DeviceSerialNumber, @DeviceType, @ElapsedTime)"
现在如何将OUTPUT INSERTED.TestId
包含在字符串(queryString
(中?
这里有一个类似的问题,但它对我的问题没有帮助
谢谢!
您可以使用
@@IDENTITY返回上次插入的标识值:
string queryString = "INSERT INTO Tests " +
"([Date], [Device], [DeviceType], [ExecutionTimeMs]) " +
"VALUES (@Date, @DeviceSerialNumber,@DeviceType, @ElapsedTime); " +
"SELECT @@IDENTITY;"
执行查询时,需要将其设置为使用 ExecuteScalar 方法返回单个值:
var newIdentity;
// set up the queryString variable & command using the above
newIdentity = cmd.ExecuteScalar();
这假定列TestId
是标识列。
虽然我接受了坦纳的回答,但我最终还是这样做了,
string queryString = "INSERT INTO Tests " + "([Date], [Device], [DeviceType], [ExecutionTimeMs]) " +
"VALUES (@Date, @DeviceSerialNumber,@DeviceType, @ElapsedTime)";
string queryString2 = "SELECT @@IDENTITY";
DbCommand command = factory.CreateCommand ();
command.CommandText = queryString;
// Added Parameters here
command.ExecuteNonQuery ();
command.CommandText = queryString2;
object testId = command.ExecuteScalar ();
所以我不得不将查询拆分为两个字符串,并使用第一个字符串运行ExecuteNonQuery
,并使用第二个字符串运行ExecuteScalar
。