2015-09-29 250 views
0

我正在使用以下代碼將一行插入到數據庫中,並使用GETDATE()設置日期。如果不運行第二個單獨的查詢以將該日期撤回,那麼在同一個查詢中是否有方法讓它返回剛剛插入的日期?在INSERT查詢中使用GETDATE(),它可以將該日期返回給我嗎?

int resultCompletedDate = 0; 

using (SqlConnection connect = new SqlConnection(connectionString)) 
{ 
    string updateQueryCompletedDate = @"UPDATE Conversions 
             SET CompletedDate = GETDATE(), 
             Status = 'Completed' 
             WHERE ID = @ID"; 

    SqlCommand command1 = new SqlCommand(updateQueryCompletedDate, connect); 
    command1.Parameters.AddWithValue("ID", item1.ID); 

    connect.Open(); 
    resultCompletedDate = Convert.ToInt32(command1.ExecuteScalar()); 
    connect.Close(); 
} 
+1

順便說一句,是一個更新查詢:) –

+0

哈哈哎呀!我錯過了那個 – Jrow

回答

2

使用批處理語句作爲命令文本。由於不使用反斜槓或雙引號,因此不需要逐字字符串。

DECLARE @completedDate datetime = GETDATE(); 
UPDATE Conversions SET CompletedDate = @completedDate, Status = 'Completed' WHERE Id = @id; 
SELECT @completedDate; 

不要使用Convert.ToInt32,只需使用Convert.ToDateTime代替。

普羅蒂普:使用using,而不是手動關閉連接,因爲現在你的連接不會,如果ExecuteScalar關閉拋出一個異常:

using(SqlConnection c = new SqlConnection(...)) 
using(SqlCommand cmd = c.CreateCommand()) { 
    cmd.CommandText = "DECLARE @completedDate..."; 
    cmd.Parameters.AddWithValue("@id", item1.ID); 
    c.Open(); 
    DateTime completedDate = Convert.ToDateTime(cmd.ExecuteScalar()); 
    return completedDate; 
} 
+2

Cleaver,+1。 OP也可以使用['OUTPUT'子句](https://msdn.microsoft.com/en-us/library/ms177564.aspx) –

+1

@RubensFarias我認爲'OUTPUT'實際上更乾淨。請提交,作爲一個新的答案:) – Dai

+0

一個更清潔的選擇將在過程中有這個批處理sql代碼,而不是有多個sql語句。 – Rahul

1

您還可以使用OUTPUT clause

using (var connect = new SqlConnection(connectionString)) 
{ 
    connect.Open(); 
    var command1 = new SqlCommand(@" 
     UPDATE  Conversions 
      SET  CompletedDate = GETDATE(), 
        Status = 'Completed' 
      WHERE ID = @ID 
      OUTPUT INSERTED.CompletedDate", connect); 
    command1.Parameters.AddWithValue("ID", item1.ID); 

    resultCompletedDate = Convert.ToDateTime(command1.ExecuteScalar()); 
} 
0

爲什麼不將日期傳遞給查詢呢?

DateTime completeDate = DateTime.Now; 

using (SqlConnection connect = new SqlConnection(connectionString)) 
{ 
    string updateQueryCompletedDate = @"UPDATE Conversions 
             SET CompletedDate = @CompleteDate, 
             Status = 'Completed' 
             WHERE ID = @ID"; 

    SqlCommand command1 = new SqlCommand(updateQueryCompletedDate, connect); 
    command1.Parameters.AddWithValue("ID", item1.ID); 
    command1.Parameters.AddWithValue("CompleteDate",completeDate); 

    connect.Open(); 
    command1.ExecuteNonQuery(); 
    connect.Close(); 
} 

唯一的區別是客戶端和服務器之間可能存在時區差異。

+0

在這種特殊情況下,不同的時區可能是一個問題 – Jrow

相關問題