比较sql插入日期和c#日期时间

时间:2016-06-09 16:30:15

标签: c# mysql

我正在交易网站上工作。创建订阅时,修改日期将插入表中。我想要完成的是唯一地识别该记录。这是我正在尝试的:

DateTime currentTime = DateTime.Now;
Debug.WriteLine("Current Timestamp is: " + currentTime.ToString("yyyy-MM-dd HH:mm:ss:fff"));

sCmd.CommandText = "SELECT distinct userID FROM table WHERE Report_OID = @reportID AND ModifiedDate = @currentTime";
sCmd.Parameters.AddWithValue("@reportID", reportID);
sCmd.Parameters.AddWithValue("@currentTime", currentTime.ToString("yyyy-MM-dd HH:mm:ss:fff"));

Output: 

Current Timestamp is: 2016-06-09 10:19:16:586
Modified Date is: 2016-06-09 10:19:16.553

试过这个:

sCmd.CommandText = "SELECT LAST_INSERT_ID();";
IDataReader reader = sCmd.ExecuteReader();
while (reader != null &&  reader.Read())
{
    long lastInsertedID = reader.GetInt64(0);
    Debug.WriteLine("return id is : " + lastInsertedID);
}

Got this error:
'LAST_INSERT_ID' is not a recognized built-in function name.

This error may have happened due to the createSubscription method call to create a subscription in the reporting service webservice which handles the insert in the database. I do not have insert statements in my code. 

这将失败,因为毫秒不会相同。我想使用毫秒的原因是,如果两个用户在同一时间插入订阅,则会阻止多个用户ID。

我想弄清楚的是比较这两个日期,这样我就可以准确地获取我的交易的用户ID,而不用担心如果同时插入两个交易,就抓住其他用户ID。这可能吗?我试图以错误的方式解决这个问题。任何帮助将不胜感激。谢谢。

3 个答案:

答案 0 :(得分:0)

原谅我的伪代码(我不经常使用MySQL),但正确的方法是修改你的插入以返回你的语句插入的最后一条记录的标识,而不是试图匹配东西使用时间戳和userIds。代码将更简单,更可靠。这是在MySQL中使用LAST_INSERT_ID()函数(MS SQL的SCOPE_IDENTITY()函数的近似值)完成的。

例如,你的插入(假设表有一个名为“FooID”的缩进列可能看起来像这样:

INSERT INTO Foo (Bar) VALUES ('Biz');
SELECT LAST_INSERT_ID();

如果新记录的FooID为148,那么您的语句将插入记录并返回148,此时您可以:

SELECT Bar FROM Foo WHERE FooID = 148;

那应该完成你想要做的事。

答案 1 :(得分:0)

只需使用其中一个输入即可找到记录。你有几个。

答案 2 :(得分:0)

感谢@Paparazzi,我创建了另一个select语句,通过使用电子邮件地址获取最新的订阅,并在调用createSubscription方法之前创建一个datetime变量我能够获得最新的插入ID及其现在正在工作。

DateTime subscriptionCreateTime = DateTime.Now;
CreateSubscription(); //Create a new ssrs subscription

//SQL connection here
sCmd.CommandText = "SELECT distinct ownerID FROM db.table WHERE Report_ID = @reportID AND ModifiedDate >= @currentTimeStamp AND Description like @emailAddress";
sCmd.Parameters.AddWithValue("@reportID", gRptID);
sCmd.Parameters.AddWithValue("@emailAddress", "%"+tbTO.Text+"%");
sCmd.Parameters.AddWithValue("@currentTimeStamp", subscriptionCreatedTime);
SqlDataReader reader = sCmd.ExecuteReader();
相关问题