I'm trying to convert the following stored procedure into a query, so that I can use it in 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
From the above script, all I can understand is that it takes three input parameters
but it'll update 5 columns in the table Tests
including Date
and TestId
.
Since I can't use stored procedures in SQL Server CE, I've converted the above script into a string query,
string queryString = "INSERT INTO Tests ([Date], [Device], [DeviceType], [ExecutionTimeMs]) VALUES (@Date, @DeviceSerialNumber, @DeviceType, @ElapsedTime)"
Now how to include OUTPUT INSERTED.TestId
into the string( queryString
) ?
There's a similar question here , but it doesn't help my problem
Thanks!
You can use @@IDENTITY to return the last inserted identity value:
string queryString = "INSERT INTO Tests " +
"([Date], [Device], [DeviceType], [ExecutionTimeMs]) " +
"VALUES (@Date, @DeviceSerialNumber,@DeviceType, @ElapsedTime); " +
"SELECT @@IDENTITY;"
When you execute your query, you need to set it up to return a single value using the ExecuteScalar method:
var newIdentity;
// set up the queryString variable & command using the above
newIdentity = cmd.ExecuteScalar();
This assumes that the column TestId
is an identity column.
Though I accepted Tanner's answer, but I ended up doing like this,
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 ();
So I had to split the query into two string & run ExecuteNonQuery
with the first string and run ExecuteScalar
with the second string.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.