2012-03-14 75 views
1

我有一个具有不同属性的类,可以说。C#检查插入值为空或空的原因用空字符串覆盖

Object.attributeA 
Object.attributeB 
Object.attributeC 
Object.attributeD 

然而,它们并不总是被填满。例如:

Object.attributeA = "string"; 
Object.attributeB = "string"; 
Object.attributeC = null; 
Object.attributeD = "string"; 

我的INSERT语句是这样的:

string sql = @"INSERT INTO TABLE 
     (
attributeA, 
attributeB, 
attributeC, 
attributeAD 
) 
values 
(
@attributeA, 
@attributeB, 
@attributeC, 
@attributeAD 
);"; 
SqlParameter[] parameters = 
{ 
new SqlParameter("@attributeA", SqlDbType.NVarChar) {Value = attributeA}, 
new SqlParameter("@attributeB", SqlDbType.NVarChar) {Value = attributeB}, 
new SqlParameter("@attributeC", SqlDbType.NVarChar) {Value = attributeC}, 
new SqlParameter("@attributeD", SqlDbType.NVarChar) {Value = attributeD} 
}; 
ExecuteNoNQuery(sql, parameters); 

如何插入一个空?

(为了证实:当我更新行我想保留旧的值,如果新值为空,用“?”我只是简单地覆盖旧值右)

旧行 “ABC”“ ABC” “ABC” “ABC”

更新行: “串” “串” “ABC” “串”

AND NOT: “串” “串” “” “串”

编辑: 我hav两张桌子。我使用第一个表的插入,添加属性(排序的临时保存),然后我把这个表行用于行更新'真正'的表。表1中的属性总是多于真实的表。这就是为什么在插入“”之后,我只是覆盖真实表格中的属性。

我的更新功能看起来是这样的:

public void UpdateBatchToRealTable(Class, int id) 
    { 
     // Current Batch 
     DataTable dt = DAL.Batch(id); 

     // table 1 (temp table) -> table 2 (real table) 
     DataRow row = dt.Rows[0]; 

     Object.attributeA = row["attributeA"].ToString(); 
     Object.attributeB = row["attributeB"].ToString(); 
     Object.attributeC = row["attributeC"].ToString(); 
     Object.attributeD = row["attributeD"].ToString(); 
    } 
+0

对于你首先得把所有的列值(以前),然后根据您的要求进行更新。我认为最好的方法是使用SP,它会拒绝空更新,而不是先回顾价值,然后再进行检查。 – Zenwalker 2012-03-14 10:09:09

+0

只是为了确定我的理解。当INSERT为空时OK,UPDATE为空时不行吗? – Steve 2012-03-14 10:09:55

+0

您的声明是INSERT语句。在这种情况下,不会有任何旧的价值! – 2012-03-14 10:13:42

回答

0

使用DBNull.Value价值在哪里,你想传递NULL值的参数........

+0

这样的事情? //如果值不为空,则清除覆盖? (row [“attributeA”]!= DBNull.Value) Oject.attributeA = row [“attribute”]。ToString(); } – Danny 2012-03-14 10:57:29

0

您可以使用双待标记运算符。

Value = attributeA ?? DBNull.Value 

这将分配'??'的右边的值,是左边的值(在这个例子中属性A)是空的。

如果您希望在对象可能为空时指定不同的默认值,则可以在各种场所使用此功能。

2

如果我明白你的问题(你似乎在询问有关更新,但你的样品是一个INSERT),你可以这样做:

UPDATE Table 
SET AttributeA = ISNULL(@AttributeA, AttributeA) 
... 

将离开AttributeA不变,如果@AttributeA参数为NULL( DBNull.Value)。

或者,如果你想忽略空字符串:

UPDATE Table 
SET AttributeA = CASE WHEN LEN(@AttributeA) = 0 THEN AttributeA ELSE @AttributeA END 
... 

或者,如果你想忽略null和空字符串:

UPDATE Table 
SET AttributeA = CASE WHEN LEN(ISNULL(@AttributeA,'')) = 0 THEN AttributeA ELSE @AttributeA END 
...