2012-03-14 56 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 
...