0

I am new to SQL and have started a kind of test project to get my hands dirty working with SQL and C#. I have been using VS2012's database wizards to set everything up. So here's the rundown of my setup.

SQL CE table named ACDTable and it is connected to my C# project by a dataset dataSet1 and a table adapter dataTableAdapter

ACDTable has 22 columns and what I am trying to do is for each row that has a value (is not null) for each column I specify it adds one to a counter and then adds the sum to another column I specify.

Essentially I need to find how many columns are not null for each row and turn that number into something usable in C#.

Example:

 |Col1 | Col2 | Col3| Col4| Col5|
 |     |      |     |     |     |
 |  x  |   x  |     |  x  |  3  |
 |     |   x  |  x  |     |  2  |
 |  x  |      |     |     |  1  |

I am using the example Count of non-null columns in each row and it does work great if I just run it as a query via SQL.

The example I am using:

SELECT   Col1,
         Col2,
         Col3,
         Col4,


     CASE WHEN Col1 IS NOT NULL THEN 1 ELSE 0 END + 
     CASE WHEN  Col2 IS NOT NULL THEN 1 ELSE 0 END + 
     CASE WHEN  Col3 IS NOT NULL THEN 1 ELSE 0 END + 
     CASE WHEN  Col4 IS NOT NULL THEN 1 ELSE 0 END AS Col5
 FROM     ACDTable

The problem I am running into is when I use Visual Studio to create a method based on this Query and I try to get the values of Col5 via that method I am getting a NullDB exception. If I run the debugger and look at the table after I have called the method the Col5 is completely null. I have a feeling the problem is the query itself is not actually changing the 5th column but my inexperience with SQL is showing and I cannot figure out the correct syntax to fix this.

Fixed typo where I had Col5 in the SELECT list

Edit to show the code I am using

The method itself is the one generated by Visual Studio using the Add Query option in the Table Adapter. It is if I understand correctly supposed to run the above query and then put the values into Col5 for me. I then just want to to see those values represented in a richtextbox using

GetTotals(); //The Generated method from VS that runs my query
var totals = from p in dataTable select p.Col5;
   foreach (var total in totals)
     {
       testTextBox.Text = total
     }
4

3 回答 3

1

如果我正确理解了您的评论,那么我知道问题出在哪里。此时,您只是从表中选择值,而不是向其中写入任何值。一种方法是创建一个 UPDATE 查询并将 Col5 的值设置为 case 语句。

UPDATE ACDTable
SET Col5 = CASE WHEN....

我想你知道如何完成这件事。如果必须,您仍然可以在最后添加 WHERE 子句。

于 2013-09-20T18:41:02.337 回答
0

Column 5在选择列表中有两次。一次作为命名列,一次作为计算列。你是在创建这篇文章时犯了那个错字,还是在你的代码中是这样的?

于 2013-09-20T13:21:44.363 回答
0

因为 Col5 没有大小写(条件)。您有 col1,col2,col3,col4 而没有 col5,您只需将 col4 名称指定为 col5,在这种情况下这是一个坏主意。

于 2013-09-20T13:23:56.723 回答