2

我正在创建一个程序,该程序需要检查数据库的第 1 列中是否存在值,如果不存在则添加它,或者如果存在则将 1 添加到第 2 列中的值。

目前该程序只将每个值添加到数据库中,我不知道如何做下一部分,它应该做一些类似的事情:

if column 1 contains (textbox)
column 2 = column 2 + 1

else column 1 doesnt contain (textbox)
add to column 1

我只是在学习 C#,这几乎是我必须做的第一个 SQL,所以请保持任何答案简单。

这是当前工作的代码的一部分。

System.Data.SqlClient.SqlCommandBuilder cb;
cb = new System.Data.SqlClient.SqlCommandBuilder(da);
DataRow dRow = ds1.Tables["Tags"].NewRow();
dRow[0] = txtSplittext.Text;
dRow[1] = 1;
ds1.Tables["Tags"].Rows.Add(dRow);
MaxRows = MaxRows + 1;
inc = MaxRows - 1;
da.Update(ds1, "Tags");

感谢你给与我的帮助。

4

1 回答 1

0

You want a basic update statement in SQL:

update table
    set column_2 = (case when charindex([textbox], column_1) > 0 then column_2 + 1 else column_2 end),
    set column_1 = (case when charindex([textbox], column_1) = 0 then column_1 + 1 else column_1 end)

(You could alternatively use the SQL "like" command, which should work in all dialects. I've chosen a Microsoft equivalent that is likely to be more efficient.)

In the above SQL, [textbox] represents the value in the text box. You can insert it into such a query either using dynamic SQL or as a parameter.

I am also assuming that you only want to do this for one row. If so, then this needs a where clause to identify the row (preferably with a primary key).

于 2012-04-29T20:53:44.563 回答