i storing date in db as below code
convert(varchar(10),GETDATE(),105)
now i need to search values
ALTER PROCEDURE spr_tb_sales
#to_date date,
#from_date date
AS
BEGIN
SELECT *
FROM tb_sales_
WHERE [Sales Date] BETWEEN #from_date AND #to_date
END
If I pass in the values 01-01-2014 and 10-01-2014 it's showing error
Incorrect syntax near '-'.
where i made error.help me
You are storing date as a varchar field. This doesn't seem to be a good idea and I believe between won't work on that. You should store date using the datetime type. Let SQL decide how to store it and you can format it as you wish while displaying.
I think from what you are saying it seems like you are passing the dates in incorrectly. when you call your stored procedure, it should look like this:
exec spr_tb_sales '01-01-2014', '10-01-2014'
I think you might be missing the quotes around your dates which would give you the error that '-' is not correct syntax.
Related
The date format in the table is YYYYMMDD and I would like to convert it to the following format but it is failing with an error:
2019-07-23 00:00:00.000
Conversion failed when converting date and/or time from character string
Here is the statement I'm using:
convert(varchar(10), convert(datetime, InstallDate0), 23)
The real problem is the choice of your datatype. varchar is the wrong choice. As a result, it seems that you now have some rows where the value of the "date" has been lost, as it can't be converted to a date.
To properly fix this problem, fix your datatype. Firstly I would create a new column to store the bad values:
ALTER TABLE YourTable ADD BadDate varchar(20); --as it's yyyyMMdd you don't need more than 8 characters, but we'll assume you have some really bad values
UPDATE YourTable
SET BadDate = InstallDate0
WHERE TRY_CONVERT(datetime,InstallDate0) IS NULL;
Now that you've done that, time to update the existing column:
UPDATE YourTable
SET InstallDate0 = CONVERT(varchar(8),TRY_CONVERT(datetime, InstallDate),112);
This'll set every value to the yyyyMMdd format where the value can be converted. NOw you can alter your table:
ALTER TABLE YourTable ALTER COLUMN InstallDate0 date; --AS it's yyyyMMdd, it seems silly to actually use datetime
Now you have a proper datetime column.
You'll then need to inspect the values of BadDate and try to correct them (or admit that any information they held has been lost for ever).
If you "must" have another column with the format, then add a further column:
ALTER TABLE YourTable ADD InstallDate0_f AS CONVERT(varchar(23),InstallDate0,121);
You can determine where the problems are using TRY_CONVERT(). The problem would seem to be the conversion to a datetime, so try this:
select InstallDate0
from t
where try_convert(datetime, InstallDate0) is null;
[Using SQL Server 2008 R2 Enterprise x64 SP1]
I am trying to use some form of GETDATE() to pass today's date to a stored procedure inside OPENQUERY(), but I keep getting the error
Msg 8114, Level 16, State 1, Procedure spCalcProjection, Line 0
Error converting data type nvarchar to datetime
Here is the code (spCalcProjection takes a datetime):
SELECT top 1 multi FROM OPENQUERY([production], 'exec proddb.dbo.spCalcProjection "GETDATE()"')
If I use 2014-05-22 or any literal in place of GETDATE() then I have no problem and get the correct, expected result. If I use some other functionality like CAST(GETDATE() AS DATE) or CONVERT(varchar, GETDATE(), 112) then I get the above error again.
Conrad, posting original syntax error for GETDATE() without double quotes could help more than you think. I also don't see why would you need to escape the function here. (Sorry, can't add to your thread with Lamak, not enough reputation for comments). Also, why do you need an open query to call your sp? When you say SQL Server 2008 R2, is it both on the calling side and on your [production] server? If the other end is not SQL Server it might not have GETDATE() function. If the other end is SQL Server you don't need OpenQuery.
[UPDATE]
I think I have your answer. You cannot use a function as a parameter for stored procedure. Has nothing to do with open query. What you can do, you can replace that stored procedure with table-valued function. I just tried it and it worked.
Definition:
CREATE FUNCTION TestFun
(
#TestDateParam datetime
)
RETURNS
#RetTable TABLE
(
Line nvarchar(20)
)
AS
BEGIN
INSERT INTO #RetTable
SELECT aString
FROM sometable
WHERE aDate = #TestDateParam
RETURN
END
Call:
SELECT *
FROM dbname.dbo.TestFun(GETDATE())
Got an answer from elsewhere that I will use:
SELECT top 1 multi FROM OPENQUERY([production], 'DECLARE #dt datetime SELECT #dt = GETDATE() exec proddb.dbo.spCalcProjection #dt')
This avoids having to create any additional objects in the db.
alter PROCEDURE [dbo].[select_User_attendance_master_Date]
(
#From_date NVarchar(100),
#To_date NVarchar(100)
)
as
begin
select
Employee_Attendace_Code,
Convert(varchar(11),Employee_Attendance.Attendance_day,106) as Attendanceday
from Employee_Attendance
(Convert(varchar(11),Employee_Attendance.Attendance_day,106) between '%'+#From_date+'%'
AND '%'+#To_date+'%')
end
this query is not working it is getting nothing in Attendance_day values are eg 2013-11-28
Please rethink your question.
LIKE is great to operate over strings but ill not work well for dates.
depending on your data it can return a from date is greater than to date.
Try to use date/datetimes variables, if you receive dates as a string, convert that dates to date/datetime data type and just put that values in the between.
And receive that dates parameters as date/datetime types if you can.
I believe you are looking for this?
You where missing the WHERE clause and I corrected a typo for your first column selected.
ALTER PROCEDURE [dbo].[select_User_attendance_master_Date]
(
#From_date NVarchar(100),
#To_date NVarchar(100)
)
AS
BEGIN
SELECT
Employee_Attendance_Code,
Employee_Attendance.Attendance_day as Attendanceday
FROM Employee_Attendance
WHERE Employee_Attendance.Attendance_day BETWEEN #From_date AND #To_date
END
I want to enter 30/10/1988 as the date to a DOB column in a table using a procedure
alter procedure addCustomer
#userName varchar(50),
#userNIC varchar(50),
#userPassword varchar(100),
#userDOB datetime,
#userTypeID int,
#userEmail varchar(50),
#userTelephone int,
#userAddress char(100),
#userCityID int,
#status int output
as
declare #userID int
declare #eid int
declare #tid int
declare #aid int
execute getLastRaw 'userID','tblUserParent', #userID output
insert into tblUserParent values (#userID, #userName, #userNIC, #userPassword, #userDOB, #userTypeID)
execute getLastRaw 'addressID','tblAddress', #aid output
insert into tblAddress values (#aid, #userAddress, #userID, #userCityID)
execute getLastRaw 'emailID','tblEmail', #eid output
insert into tblEmail values (#eid, #userEmail, #userID)
execute getLastRaw 'telephoneID','tblTelephoneNO', #tid output
insert into tblTelephoneNO values (#tid, #userTelephone , #userID)
insert into tblUserCustomer values (#userID, #eid , #tid, #aid)
...but it gives an error when i enter like this '30/10/1988'
Msg 8114, Level 16, State 5, Procedure addCustomer, Line 0 Error converting data type varchar to datetime.
...but when I enter like only the 30/10/1988
Incorrect syntax near '/'
How do I fix this?
If you would truly like to avoid the possibility of ambiguous dates based, then you should always enter it in one of the two unambiguous date formats Answer has already been selected and it's valid but I'm a believer in spreading the knowledge ;)
As noticed by #cloud and my post representing a younger, and less wise me with a link only answer, I'll pop the contents of the archive of Jamie Thompson's answer for unambiguous date formats in TSQL
tl;dr;
yyyy-MM-ddTHH24:mi:ss
yyyyMMdd HH24:mi:ss
One of the most commonly used data types in SQL Server is [datetime]
which unfortunately has some vagaries around how values get casted. A
typical method for defining a [datetime] literal is to write it as a
character string and then cast it appropriately. The cast syntax looks
something like this: DECLARE #dt NVARCHAR(19) = '2009-12-08 18:00:00';
SELECT CAST(#dt AS datetime);
Unfortunately in SQL Server 2005 the result of the cast operation may
be dependent on your current language setting. You can discover your
current language setting by executing: SELECT ##LANGUAGE To
demonstrate how your language setting can influence the results of a
cast take a look at the following code: ALTER DATABASE tempdb
SET COMPATIBILITY_LEVEL = 90 ; --Behave like SQL Server 2005
USE tempdb
GO
DECLARE #t TABLE (
dateString NVARCHAR(19)
);
INSERT #t (dateString)
VALUES ('2009-12-08 18:00:00') --'yyyy-MM-dd hh24:mi:ss'
, ('2009-12-08T18:00:00') --'yyyy-MM-ddThh24:mi:ss'
, ('20091208 18:00:00') --'yyyyMMdd hh24:mi:ss'
SET LANGUAGE french;
SELECT 'french' AS lang
, DATENAME(MONTH,q.[dt]) AS mnth
, q.[dt]
FROM (
SELECT CAST(dateString AS DATETIME) AS dt
FROM #t
)q;
SET LANGUAGE us_english;
SELECT 'us_english' AS lang
, DATENAME(MONTH,q.[dt]) AS mnth
, q.[dt]
FROM (
SELECT CAST(dateString AS DATETIME) AS dt
FROM #t
)q; We are taking the value which can be described in words as “6pm on 8th December 2009”, defining it in three different ways, then
seeing how the ##LANGUAGE setting can affect the results. Here are
those results: french language datetime Notice how the interpretation
of the month can change depending on ##LANGUAGE. If
##LANGUAGE=’french’ then the string '2009-12-08 18:00:00' is
interpreted as 12th August 2009 (‘août’ is French for August for those
that don’t know) whereas if ##LANGUAGE=’us_english’ it is interpreted
as 8th December 2009. Clearly this is a problem because the results of
our queries have a dependency on a server-level or connection-level
setting and that is NOT a good thing. Hence I recommend that you only
define [datetime] literals in one of the two unambiguous date formats:
yyyy-MM-ddTHH24:mi:ss yyyyMMdd HH24:mi:ss That was going to be the end
of this blog post but then I found out that this behaviour changed
slightly in SQL Server 2008. Take the following code (see if you can
figure out what the results will be before I tell you): ALTER
DATABASE tempdb
SET COMPATIBILITY_LEVEL = 100 ; --Behave like SQL Server 2008
GO
USE tempdb
GO
SET LANGUAGE french;
DECLARE #dt NCHAR(10) = '2009-12-08 18:00:00'; --Ambiguous date
format
SELECT CAST(#dt AS datetime) AS [ExplicitCast]
, DATENAME(MONTH,#dt) AS [MonthFromImplicitCast]
, DATENAME(MONTH,CAST(#dt AS datetime)) AS
[MonthFromExplicitCast]; Here we are doing three different things with
our nchar literal: explicitly cast it as a [datetime] extract the
month name from the char literal using the DATENAME function (which
results in an under-the-covers implicit cast) extract the month name
from the char literal using the DATENAME function after it has been
explicitly casted as a [datetime] Note that the compatibility level is
set to SQL Server 2008 and ##LANGUAGE=’french’. Here are the results:
image (Were you correct?) Let’s take a look at what is happening here.
The behaviour when we are explicitly casting as [datetime] hasn’t
changed, our nchar literal is still getting interpreted as 12th August
rather than 8th December when ##LANGUAGE=’french’. The
[MonthFromExplicitCast] field is interesting though, it seems as
though the implicit cast has resulted in the desired value of 8th
December. Why is that? To get the answer we can turn to BOL’s
description of the DATENAME function syntax: image The implicit cast
is not casting to [datetime] at all, it is actually casting to [date]
which is a new datatype in SQL Server 2008. The new date-related
datatypes in SQL Server 2008 (i.e. [date], [datetime2], [time],
[datetimeoffset]) disregard ##LANGUAGE and hence we get behaviour that
is more predictable and, frankly, better. These new behaviours for SQL
Server 2008 were unknown to me when I began this blog post so I have
learnt something in the course of authoring it, I hope it has helped
you too. No doubt someone somewhere is going to get nastily burnt by
this at some point, make sure that it isn’t you by always using
unambiguous date formats: yyyy-MM-ddTHH24:mi:ss yyyyMMdd HH24:mi:ss
regardless of which version you are on!
The following works in both SQL Server and MySql without ambiguity: yyyy-mm-dd, like so:
INSERT INTO TableName(DateColumn) VALUES ('1988-10-30');
...as an added benefit there's no question of whether it's a US or European style date on days like the fourth of March...
See if there is a culture setting that you can change to allow you to use dd/mm/yyyy. I believe it is expecting mm/dd/yyyy.
A potentially easy way around the problem is to use a date format with no ambiguity between mm/dd/yyyy and dd/mm/yyyy such as dd-mmm-yyyy, eg: 30-OCT-1988
I have a SQL server stored procedure which would accept date as input param to build a query in it.So which datatype i should use for the parameter when defining stored procedure.Whats the difference between using nvarchar(15) and datetime .
1 : create procedure TestProcedure(#startDate datetime)
and
2 : create procedure TestProcedure(#startDate nvarchar(15))
IS there any advantage is i use datetime over varchar in terms of performance
Yes, always use the datetime type. Its more accurate. The datetime type is also always 8 bytes so it is smaller to transfer than 15 characters.
The front end is then responsible for handling cultural/locale issues such as MDY, DMY or YMD component field ordering. (if the database is running under a US locale and the user is in the UK does '3/4/2009' mean April 3 or March 4?)
If you know that only dates will come through the parameter, using the appropriate datatype is better as it's smaller and comparisons can be made quicker. It also prevents invalid values from being supplied.