2015-06-20 63 views
0

我有表,我想設置值,如果cell = null,然後通過文本框設置記錄。 這裏是我的表如何通過更新查詢設置記錄sql vb.net

-------------------- 
col1| col2| Note 
1  2 aaa 
5  5 (*) set record Only here if cell is Null 
42  14 
47  55 
------------------ 

這裏是我的代碼,我的問題是每一個細胞是空查詢寫我想寫只爲下一個單元格,以前不爲空

con.Open() 
query = " update firealarm set [email protected] where Note Is Null" 
Dim command As SqlCommand = New SqlCommand(query, con) 
command.Parameters.Add(New SqlParameter("@Note", SqlDbType.NVarChar)) 
command.Parameters("@Note").Value = Notebox.Text.ToString 
command.ExecuteNonQuery() 
con.Close() 
+1

你很容易sql注入 – Sherlock

+0

'query =「更新firealarm設置注= @注意哪裏注意是空的」 – Subrati

回答

2

首先,讓我們來解決一下即時問題:在SQL中,NULL不等於任何東西,包括其他NULL s,所以Note<>Null對於所有行都是正確的。爲了解決這個問題,SQL有特殊的運算符IS NULLIS NOT NULL。使用where Note is not NULL將解決問題。

但是更大的問題仍然存在:您的程序容易受到SQL注入攻擊。要在Visual Basic中解決此問題,請參閱this Q&A

編輯:(在回答這個問題的編輯)

我想寫只爲下一個單元格,以前它是not null

的「下一個單元格」意味着一些訂單表中的單元格。由於表格行應視爲無序集合,因此讓我們假設您想按col1訂購數據在您的示例中的排序方式。

查詢條件成爲這個更大:

UPDATE f 
SET [email protected] 
FROM firealarm f 
WHERE Note Is Null 
    AND NOT EXIST (
    SELECT * FROM firealarm ff WHERE ff.col1 < f.col1 AND ff.Note IS NULL 
) 

WHERE條件說,需要更新時對電池進行與在Note列最低col1NULL值。

+0

你能成爲我的導師嗎? :3 – Sherlock

+0

@dasblinkenlight ---- query =「update firealarm set Note = @ Note Note Note Null」----問題是所有單元格中的記錄都是空的,我只想設置下一個單元格後不爲空並保持所有的空單元格 – Subrati

+0

@Subrati你需要'注意不是NULL'。之後,添加'query.Parameters.Add(「@ Note」,SqlDbType.VarChar,50).Value = Notebox.Text'來設置'@ Note'參數的值。 – dasblinkenlight

0

要更新確切行,你需要在WHERE語句的詳細情況

UPDATE firealarm SET [email protected] 
WHERE Note IS NULL 
AND Col1 = @ValueOfCol1 
AND Col2 = @ValueOfCol2 

vb.net代碼

con.Open() 
Dim query As String = <![CDATA[UPDATE firealarm SET [email protected] 
WHERE Note IS NULL 
AND Col1 = @ValueOfCol1 
AND Col2 = @ValueOfCol2]]>.Value 
Dim command As SqlCommand = New SqlCommand(query, con) 
With command.Parameters 
    .Add(New SqlParameter With {.ParameterName = "@Note", 
           .SqlDbType = SqlDbType.NVarChar, 
           .Value = Notebox.Text}) 
    .Add(New SqlParameter With {.ParameterName = "@ValueOfCol1", 
           .SqlDbType = SqlDbType.Int, 
           .Value = 5}) 
    .Add(New SqlParameter With {.ParameterName = "@ValueOfCol2", 
           .SqlDbType = SqlDbType.Int, 
           .Value = 5}) 
End With 
command.ExecuteNonQuery() 
con.Close() 

或身份列的利用價值,如果你的表有這個

0

嘗試此查詢,它會更新只是第一行,爲空

WITH UpdateList_view AS 
(SELECT TOP 1 * from Fire alarm  
    Where NOTE is Null) 


update UpdateList_view 
set [email protected]  
+0

如何確保你可以更新的行將需要一個? – Fabio

+0

沒有不能保證,沒有幾個細節,希望必須有一些id列 –