Reputation: 415
This is my first approach to SQL Server. I have exported my Access DB to SQL Server and want to use it in my application. I have added the new SQL DB to my C# project and replaced OleDB
with Sql
. I am now unable to execute queries which where perfectly working with local DB in Access.
Query:
string query = @"SELECT SessionID, SemesterA, SemesterB, RoomID, SessionDate, SessionTimeStart, SessionTimeEnd" +
" FROM [Session] " +
" WHERE RoomID = @RoomID " +
" AND SessionDate = getdate() ";
I have replaced Date()
with getdate()
as instructed by the VS error, but the query does not produce any result (should return one record, Access DB does)
My RoomSelect form code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AutoReg
{
public partial class RoomSelect : Form
{
DataTable queryResult = new DataTable();
public string RoomID;
RoomActiveSession RoomActiveSessionForm = new RoomActiveSession();
public RoomSelect()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
switch (listBox1.SelectedItem.ToString())
{
case "MB0302":
RoomID = listBox1.SelectedItem.ToString();
roomQuery();
break;
case "MC1001":
RoomID = listBox1.SelectedItem.ToString();
roomQuery();
break;
case "MC3203":
RoomID = listBox1.SelectedItem.ToString();
roomQuery();
break;
case "MC3204":
RoomID = listBox1.SelectedItem.ToString();
roomQuery();
break;
}
}
public void roomQuery()
{
string ConnStr = "Data Source=DUZY;Initial Catalog=AutoRegSQL;Integrated Security=True";
SqlConnection MyConn = new SqlConnection(ConnStr);
MyConn.Open();
//SQL query that todays sessions for the given roomID
string query = @"SELECT SessionID, SemesterA, SemesterB, RoomID, SessionDate, SessionTimeStart, SessionTimeEnd" +
" FROM [Session] " +
" WHERE RoomID = @RoomID " +
" AND SessionDate = getdate() ";
SqlCommand command = new SqlCommand(query, MyConn);
command.Parameters.Add("RoomID", SqlDbType.Char).Value = RoomID;
SqlDataAdapter adapter = new SqlDataAdapter(command);
adapter.Fill(queryResult);
if (queryResult.Rows.Count == 0)
{
MessageBox.Show("No active sessions today for the given room number");
MyConn.Close();
}
else
{
RoomActiveSessionForm.SetDataSouce(queryResult);
this.Hide();
RoomActiveSessionForm.ShowDialog();
MyConn.Close();
}
}
}
}
When I run the program, I receive a message "No active sessions today for the given room number" which should be executed when there are no results to the query, but I know for a fact, that it should return one record)
Upvotes: 2
Views: 1415
Reputation: 1269503
The function getdate()
actually returns a datetime
. Try converting it to a date:
AND SessionDate = cast(getdate() as date)
The time component is probably the problem -- preventing a match between the date and the datetime.
Upvotes: 6