【发布时间】:2015-08-19 12:32:13
【问题描述】:
我有下面的 C# 代码来检查记录是否不存在,插入并返回 id。但我也需要如果记录存在,它会返回值。为了发生这种情况,我应该对 C# 和 SQL 部分进行哪些更改?数据库是 SQL 服务器。我还需要为此使用 ExecuteScalar() 吗?
con.Open();
// Insert ClinRefFileTypeMaster
string command1 = string.Format(
"if NOT exists (select * from [ClinRefFileTypeMaster] where [ClinRefTypeName] = '{0}') Insert into [ClinRefFileTypeMaster] ([ClinRefTypeName]) output INSERTED.[ClinRefTypeID] VALUES('{0}')",
dataToParse[i][0]
);
SqlCommand ClinRefFileTypeMaster = new SqlCommand(command1, con);
// check if there is an value
object checkValue = ClinRefFileTypeMaster.ExecuteScalar();
if (checkValue != null)
ClinRefFileTypeId = (int)checkValue;
【问题讨论】:
-
可能你需要 MERGE 语句
-
也许拆分语句。仅插入 if 块。选择外面。 SQL 在缓存方面非常好,如果您刚刚插入一些选择它可能会非常快。另外查询很难阅读,请以@开头。
-
这个样子Little Bobby Tables 不知道。
-
类似的解决方案是here
-
或者使用 DECLARE recordId int;然后 SELECT recordId = idColumn FROM tbl...
标签: c# sql-server visual-studio-2013