2014-10-22 60 views
1

我想下面的存儲過程轉換成一個查詢,這樣我就可以在SQL Server CE將存儲過程轉換爲查詢(SQL Server Compact)?

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 

使用它從上面的腳本,所有我能理解是,它需要三個輸入參數

  1. DeviceSerialNumber
  2. 設備類型
  3. ElapsedTime

,但它會更新表Tests中的5列,包括DateTestId

既然不能使用SQL Server CE的存儲過程,我已經轉換上面的腳本到一個查詢字符串,

string queryString = "INSERT INTO Tests ([Date], [Device], [DeviceType], [ExecutionTimeMs]) VALUES (@Date, @DeviceSerialNumber, @DeviceType, @ElapsedTime)" 

現在如何將OUTPUT INSERTED.TestId到字符串(queryString)?

有一個類似的問題here,但它並不能幫助我的問題

謝謝!

+0

您可以改爲使用[SQL Server Express](http://www.microsoft.com/en-gb/server-cloud/products/sql-server-editions/sql-server-express.aspx)。 – Tanner 2014-10-22 10:50:41

+0

是的,那已經可用了,但我正在尋找在SQL CE中提供解決方案。 – SanVEE 2014-10-22 10:52:19

+2

您可以在INSERT後立即使用SELECT @@ IDENTITY來返回TestId,假設這是一個標識列? – 2014-10-22 10:57:17

回答

2

您可以使用@@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是標識列。

+0

我推薦使用**'SCOPE_IDENTITY()'* *而不是其他任何東西來抓取新插入的身份值。 [請參閱此博客文章,瞭解有關WHY的解釋](http://blog.sqlauthority.com/2007/03/25/sql-server-identity-vs-scope_identity-vs-ident_current-retrieve-last-inserted-identity -of-record /) – 2014-10-22 11:11:29

+0

@marc_s我不確定當範圍身份不在存儲過程中時是否可以工作,但我會根據您的金牌更新它。 – Tanner 2014-10-22 11:13:20

+0

'SCOPE_IDENTITY' **絕對**在「正常」專用SQL語句中工作 - 完全沒有問題... – 2014-10-22 11:14:09

1

雖然我接受坦納的答案,但我終於實現了這個樣子,

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

相關問題