Reputation: 11
I am connecting to an SQL server. I have a column which has date and time and another which has the user name. Once i connect to the database it shows everything except the null values in the column of date and time. I need to show only the column of data and time which holds null values and the user with the null value. How do i Display the null values but only the null values?
Below is my code:
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace sql_connection
{
class Program
{
static void Main(string[]args)
{
string conn=null;
SqlConnection connection;
conn=("Data Source=Database\\SQL2012;Initial Catalog=Table;User ID=user;Password=example");
connection=new SqlConnection(conn);
try{
connection.Open();
Console.Writeline("Connection Open!");
SqlCommand cmd= new SqlCommand("SELECT tabledateandtime,tableuser FROM [dbo].[tb_Showingnull]");
cmd.Connection = connection;
SqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
Console.WriteLine("{1} , {0}", reader["tabledateandtime"].ToString(), reader["tableuser"].ToString()));
}
connection.Close();
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
Upvotes: 0
Views: 963
Reputation: 32713
Based on OP's last comment, I have updated the code below to display NULL if the date is NULL otherwise show the date.
while(reader.Read())
{
Console.WriteLine("{1}, {0}",
reader["tableuser"].ToString(),
reader["tabledateandtime"] == DBNull.Value ? "NULL" : reader["tabledateandtime"].ToString());
}
If you just want to return only records that have a null date, then just update your SQL to this:
SqlCommand cmd = new SqlCommand("SELECT tabledateandtime, tableuser" +
" FROM [dbo].[tb_Showingnull] WHERE tabledateandtime IS NULL OR tableuser IS NULL");
Upvotes: 1
Reputation: 3589
I think I finally understood what you want - check this out:
while(reader.Read())
{
Console.WriteLine("{1} , {0}", reader["tabledateandtime"] == DBNull.Value ? "NULL" : reader["tabledateandtime"].ToString(), reader["tableuser"].ToString()));
}
Upvotes: 0