System.Data.SqlClient.SqlException(Date_Format) - c#

I am using Sql-Server 2012 and have a query
string sqlQuery = "SELECT distinct DATE_FORMAT(collectiondate,'%m/%d/%Y') FROM reports where patientid= " + patientId + " and isdeleted=false order by collectiondate desc";
var lst = Session.CreateSQLQuery(sqlQuery).List();
ArrayList rpt = new ArrayList();
rpt.Add("--ALL--");
but I am getting an error
System.Data.SqlClient.SqlException: 'DATE_FORMAT' is not a recognized built-in function name.
Can someone help me out?

You should rather try using CONVERT
SELECT CONVERT(VARCHAR(8),GETDATE(),1)
SQL Fiddle DEMO
That being said, I would recomend returning the values as is from the Database, and leaving the formatting to the UI.

There's no DATE_FORMAT function in SQL Server.
You need to use CONVERT function
SELECT distinct SELECT CONVERT(VARCHAR(8), collectiondate, 1) ...
Also, formatting is best to be done in the code, not in SQL Server. You should return your date as DATE or DATETIME column and format it in your code.

You can use the FORMAT() command in SQL Server 2012 instead.
DECLARE #d DATETIME = GETDATE();
SELECT FORMAT(#d, 'mm/dd/yy', 'en-US') AS 'Result';

Related

How to get date from textbox and use it for SELECT Statement

I made a programm, which shows a table from my database.
The Statement looks like that:
string sql = ("select CCase.RefNo AS Az, EventTemplate.EventCode AS
Vorgang from ikaros.CCase join ikaros.Event on CCase.ID =
Event.CCaseID join ikaros.EventTemplate on Event.EventTemplateID =
EventTemplate.ID where EventTemplate.EventCode='IRVB' and
Event.EventDate ='2014-07-03' order by CCase.RefNo ASC");
Now with
Event.EventDate='2014-07-03'
I get the table of that Date which is given in the SELECT Statement.
But I want give the user the opportunity to give a other Date in a Textbox.
The Textbox should change the Date in the Statement.
I looked here:
Try 1
Try 2
But it's not the same issue which I have.
If this is a duplicate and I was just to silly to find it, please tell me.
The added link in question shows your are using WPF So,
If your date is coming from TextBox then you should use TextBox.Text property to read date from user input like
var date = TextBox1.Text;
OR
If you used DatePicker then you can use DatePicker.SelectedDate.Value.Date property to read user input
var date = DatePicker1.SelectedDate.Value.Date;
And then pass this to sql query like
string sql = ("select ... where EventTemplate.EventCode='IRVB' and
Event.EventDate ='"+ date +"' order by CCase.RefNo ASC");
Note: Always use prepared statements (parameterized query) to prevent sql injection attack.
I m not sure that you are using ADO.NET but your paramterized query look like
string sql = ("select ... where EventTemplate.EventCode='IRVB' and
Event.EventDate = #date order by CCase.RefNo ASC");
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.AddWithValue("#date", date);

SQLite command to insert current datetime not working through c#

I am trying to insert current date in my table from a c# application, i am doing this the following way:
sqlite_cmd.CommandText = "INSERT INTO tablename (column1,creation_date) VALUES ('abcd_" + (id) + "',CURRENT_TIMESTAMP);";
sqlite_cmd.ExecuteNonQuery();
But this throws error saying that CURRENT_TIMESTAMP is not a valid field.
I double checked the above query using sqlite manager plugin for firefox and it seems to work correctly.
P.S. - id in the above query is an int variable that is set by c# application.
CURRENT_TIMESTAMP is only valid in column definition.
As a expression, you can use DATETIME('NOW'). Try:
sqlite_cmd.CommandText = "INSERT INTO tablename (column1,creation_date) VALUES ('abcd_" + (id) + "', DATETIME('NOW'));";
Try using this:
using(SQLiteCommand cmd = new SQLiteCommand(yourSqliteConnection))
{
cmd.CommandText = "INSERT INTO tablename (column1,creation_date) VALUES (?,?)";
cmd.Command.Parameters.AddWithValue("#p1",string.Format("abcd_{0}",id));
cmd.Command.Parameters.AddWithValue("#p2",DateTime.Now.ToString("s"));
cmd.CommandType= CommmandType.Text;
cmd.ExecuteNonQuery();
}
DateTime.Now.ToString("s") means convert this datetime into XSD format.
SQLite does not have a DateTime Format in its own. so everything you need is to convert it into a fixed format of TEXT and then insert and serach according to this format.
XSD is a fixed format for DateTime. it does not change if format of DateTime Change.
Remember when you need to do a search (SELECT) command based on DateTime try to convert it as shown above before doing any operation in SQLite.

Select DateTime column of table in 24 hour format with sql

I have a table with a column ReceivedOn of type DateTime. I am executing a stored procedure with select statement like this:
Select
CONVERT(DateTime,ReceivedOn)[Date/Time], MessageText[Event]
From
RawFeed
Where
ATM = (Select Code From ATM Where ATM = #ATMID)
AND ReceivedOn Between #From And #To
Order By
ReceivedOn Desc
I am storing stored procedure result in a DataTable object. and showing this object on my .aspx page
dtReturn = sspObj.ExecuteDataTable();
return dtReturn ;
DataTable object is converting into HTML table using some function storing result in table object and adding that to the page
tOutput = Generix.convertDataTable2HTMLTable(dtOutput, true, true, false);
Page.Controls.Add(tOutput);
But instead of displaying values as
2012-10-05 16:40:35.234
I get output like this:
2012-10-05 04:40:35 PM
It's not a SQL issue; SQL is returning a datetime, which is getting formatted by C# into the output you are seeing. If you want SQL server to return a varchar (string) representing the date in your format, try:
SELECT CONVERT(varchar(24), ReceivedOn, 121)
See Cast and Convert for more details.
Don't convert it, leave it as is.
Select ReceivedOn, ...
select
CONVERT(varchar,CONVERT(Date,ReceivedOn,101)) + ' ' +
convert(varchar,CONVERT(TIME,ReceivedOn)) AS ReceivedDate,
CONVERT(DateTime,ReceivedOn)[Date/Time], MessageText[Event]
From
RawFeed
Where
ATM = (Select Code From ATM Where ATM = #ATMID)
AND ReceivedOn Between #From And #To
Order By
ReceivedOn Desc
Try this may this will help you....

Transact SQL date query returning no results

From my code, I call an SP using:
using (var cmd = new SqlCommand("sp_getnotes"))
{
cmd.Parameters.Add("#ndate", SqlDbType.SmallDateTime).Value
= Convert.ToDateTime(txtChosenDate.Text);
cmd.CommandType = commandType;
cmd.Connection = conn;
var dSet = new DataSet();
using (var adapter = new SqlDataAdapter { SelectCommand = cmd })
{
adapter.Fill(dSet, "ntable");
}
}
The Stored Procedure itself runs a simple query:
SELECT * FROM tblNotes WHERE DateAdded = #ndate
The problem is no records are returned! DateAdded is a smalldatetime column.
When I change the query to the following, it works:
SELECT * FROM tblNotes WHERE CONVERT(DATETIME, FLOOR(CONVERT(FLOAT, DateAdded))) = #ndate
Why is this happening? This change affects the entire application and I'd like to find the root cause before getting into changing every single query... The only changes we made are to use parameterized queries and upgrade from SQL Server 2005 to 2008.
TIA.
smalldatetime has a time portion which needs to match as well.
Use this:
SELECT *
FROM tblNotes
WHERE dateAdded >= CAST(#ndate AS DATE)
AND dateAdded < DATEADD(day, 1, CAST(#ndate AS DATE))
SQL Server 2008 and above also let you use this:
SELECT *
FROM tblNotes
WHERE CAST(dateAdded AS DATE) = CAST(#ndate AS DATE)
efficiently, with the transformation to a range performed by the optimizer.
SQL Server 2008 now has a DATE data type, which doesn't keep the time porttion like SMALLDATETIME does. If you can't change the data type of the column, then you'll have to truncate when doing the compare, or simply cast to DATE:
SELECT *
FROM tblNotes
WHERE cast(dateAdded as date) = #ndate
I don't know SQL Server but from Oracle experience I'd suspect you're comparing a date time with a date, eg 01/01/2012 01:01:01 against 01/01/2012.

Error: The conversion of a nvarchar data type to a smalldatetime data type resulted in an out-of-range value

Hey all I'm trying to do the following insert query
SqlDataSource userQuizDataSource = new SqlDataSource();
userQuizDataSource.ConnectionString = "Data Source=localhost\\SQLEXPRESS;Initial Catalog=quizApp;Integrated Security=True";
userQuizDataSource.InsertCommand = "INSERT INTO [UserQuiz] ([DateTimeComplete], [Score], [UserName]) VALUES (#DateTimeComplete, #Score, #UserName)";
userQuizDataSource.InsertParameters.Add("DateTimeComplete", DateTime.Now.ToString());
userQuizDataSource.InsertParameters.Add("Score", score.ToString());
userQuizDataSource.InsertParameters.Add("UserName", User.Identity.Name);
int rowsAffected = userQuizDataSource.Insert();
Buti keep getting the following error:
The conversion of a nvarchar data type
to a smalldatetime data type resulted
in an out-of-range value.
The statement has been terminated.
Can anyone help me out?
What does your statement DateTime.Now.ToString() return??
What language and regional settings is your SQL Server expecting??
Do you have a mismatch there??? Maybe your .NET returns a MM/dd/yyyy format, while SQL Server expects dd/MM/yyyy (or vice-versa).
Try this code in your SQL Server:
DECLARE #test TABLE (smalldate SMALLDATETIME)
INSERT INTO #test VALUES ('02/21/2010 22:00:32') --
SELECT * FROM #test
Replace my string there with what output you got from .NET's DateTime.Now.ToString() - does this work? Does SQL Server give you a better error message?
Next, try to use the ISO-8601 format for dates (YYYYMMDD) - this works for ALL regional and language settings in SQL Server - does this work??
DECLARE #test TABLE (smalldate SMALLDATETIME)
INSERT INTO #test VALUES ('20100221 22:00:32') --
SELECT * FROM #test
I had the same problem adding datetime.now into my SQL server column 'Date' set to datatype SmallDateTime.
To resolve it was quite simple (after many attempts!!)
string currentdatetime=
DateTime.Now.Year + "." + DateTime.Now.Month + "." + DateTime.Now.Day +
" " + DateTime.Now.Hour+(":")+DateTime.Now.Minute+(":")+DateTime.Now.Second
This will return the date into the format that the Server will expect
Try changing this:
userQuizDataSource.InsertParameters.Add("DateTimeComplete", DateTime.Now.ToString());
to this:
userQuizDataSource.InsertParameters.Add("#startdate", SqlDbType.DateTime, DateTime.Now.ToString());
Try no converting your date to string:
userQuizDataSource.InsertParameters.Add("DateTimeComplete", DateTime.Now);
Edit: Try this then:
userQuizDataSource.InsertParameters.Add("DateTimeComplete", TypeCode.DateTime, DateTime.Now.ToString());
There is another way to just pass the actual object, but I can't remember.. sorry.
In Windows 8, if you are facing this problem even after changing Formats in below location
Control Panel -> Region
You still have to transfer these settings to your users. In the same window, go to tab "Administrative", click on copy settings.
Select the appropriate check boxes and click OK.

Categories