I have existing datatables that include a field of hexadecimal data which is actually a date.
From existing code, I know that data is converted to a DATETIME values with:
SELECT CAST(0x0000214900000000 AS DATETIME)
My problem now is that I need to insert values into such fields manually, but I don't know how to generate the hexadecimal value for a given DATETIME.
I have tried to insert AS BINARY(8) but that does not return the correct value like above.
How do I perform this conversion?
If you are doing this ALL in SQL here is a simple example that exists all in memory. You can run this as is in SQL Management Studio and the syntax should be fine for 2008 SQL Server and up.
DECLARE
#Date DateTime = getdate()
, #Hex varbinary(8)
;
DECLARE #Temp TABLE ( value varbinary(8) );
INSERT INTO #Temp VALUES (0x0000214900000000),(cast(#Date AS varbinary));
Select
value
, cast(value AS DateTime)
from #Temp
SELECT #Hex = cast(cast('2015-04-01' AS DateTime) AS varbinary)
INSERT INTO #Temp VALUES (#Hex)
Select
value
, cast(value AS DateTime)
from #Temp
You basically 'cast' an object type to a different object. Yet for varbinary if you are storing this you need to specify a length as well. You can cast back and forth in SQL quite easily if the type conversion is allowed. If you wanted to do this for insertion from .NET code directly that may be slightly different.
Related
I am using SQL server and stored procedures and I want to do a simple SELECT.
In my table I have a DATE format, which shows correctly in the database as yy-mm-dd.
When I call the stored procedure in my C# app, I also get a time value for every row (11/14/1987 12:00:00 AM).
How can I remove the time format?
Here is my select stored procedure:
ALTER procedure [dbo].[Employee_GetAllEmployees]
AS
BEGIN
SELECT * FROM
dbo.Employee
END
If you want only date then use convert() :
SELECT emp.*, CONVERT(DATE, date_col) AS New_date
FROM dbo.Employee emp;
The SQL Server date data type maps to .NET DateTime, which includes a time component. For formatting purposes in your application, use ToString according to your desired display format.
var formattedDateString = dateTypeField.ToString("yyyy-MM-dd");
Although you can format the value in T-SQL and return a string instead, burdening the database server for presentation formatting limits performance and scalability and is not considered a best practice.
So I'm writing a quick console program to collect rows of data from an old MySql database my company has and push the rows to a new Sql database. The first 300 or so rows have been fine but all of a sudden I am getting a
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
I've tried a number of ways to convert my datetimes now even though there seems to be nothing wrong with the conversion when I put it in a select.
IE:
DECLARE #INPUT varchar(30) = '09/25/2010 04:55:47';
SELECT CONVERT(datetime, #INPUT, 101);`
outputs 2010-09-25 04:55:47.000.
The conversion error is only showing up in the full Sql insert:
DECLARE #INPUT varchar(30) = '09/25/2010 04:55:47';
INSERT INTO TABLE(A_BUNCH_OF_OTHER_COLUMNS, DATETIME_COLUMN, MORE_COLUMNS)
VALUES (A_BUNCH_OF_OTHER_VALUES, CONVERT(datetime, #INPUT, 101), MORE_VALUES);`
I see no reason that this isn't working and after asking some of my coworkers, they see nothing wrong with the Sql either.
EDIT: Fixed the INSERT to reflect the actual statement.
INSERT INTO TABLE(A_BUNCH_OF_OTHER_COLUMNS, CONVERT(datetime, #INPUT, 101), MORE_COLUMNS)
In this part you should specify the column of the table which you want to insert values to. You specified the CONVERT method which is not a column.
If this is SQL Server please add the tag. What is #DT ? Are any A_BUNCH_OF_OTHER_COLUMNS | A_BUNCH_OF_OTHER_VALUES DateTimes? if so the conversion issue is likely there. – Alex K.
Thats where my problem was, there are 3 other datetime fields that are operating times that run over 24 hrs
I have one sample database with two tables like table1,table2. During calling of a stored procedure from c# passing some arguments that are inserted in table1. After that select some fields table2 values, and do some arithmetic operations like adding with some digit and multiply etc.after that return that result to C#.
How to do that in a single stored procedure?
Much the same way you would if it wasn't a stored procedure:
CREATE PROCEDURE [dev].[name_of_stored_procedure]
#an_input INT ,
#another_input DATETIME
AS
BEGIN
-- prevents the rows effected message from being returned.
-- Sometimes messes up C#
SET NOCOUNT ON;
DECLARE #magic_number INT = 47; -- declare something to do math with
-- insert into a table
INSERT INTO dev.some_table ( a_column ,
another_column
)
VALUES ( #an_input, #another_input );
-- get everything in that table that has been added for that same date
-- while doing things to it
SELECT st.a_column + #magic_number AS added_to_col ,
DATEADD(WEEK, #magic_number, st.another_column) AS added_to_date
FROM dev.some_table st
WHERE st.another_column = #another_input
ORDER BY #an_input DESC;
END;
I want to insert a datetime value into a table (SQL Server) using the SQL query below
insert into table1(approvaldate)values(18-06-12 10:34:09 AM);
But I get this Error msg:
Incorrect syntax near '10'.
I tried it with the quotes
insert into table1(approvaldate)values('18-06-12 10:34:09 AM');
I get this error message
Cannot convert varchar to datetime
You will want to use the YYYYMMDD for unambiguous date determination in SQL Server.
insert into table1(approvaldate)values('20120618 10:34:09 AM');
If you are married to the dd-mm-yy hh:mm:ss xm format, you will need to use CONVERT with the specific style.
insert into table1 (approvaldate)
values (convert(datetime,'18-06-12 10:34:09 PM',5));
5 here is the style for Italian dates. Well, not just Italians, but that's the culture it's attributed to in Books Online.
A more language-independent choice for string literals is the international standard ISO 8601 format "YYYY-MM-DDThh:mm:ss". I used the SQL query below to test the format, and it does indeed work in all SQL languages in sys.syslanguages:
declare #sql nvarchar(4000)
declare #LangID smallint
declare #Alias sysname
declare #MaxLangID smallint
select #MaxLangID = max(langid) from sys.syslanguages
set #LangID = 0
while #LangID <= #MaxLangID
begin
select #Alias = alias
from sys.syslanguages
where langid = #LangID
if #Alias is not null
begin
begin try
set #sql = N'declare #TestLang table (langdate datetime)
set language ''' + #alias + N''';
insert into #TestLang (langdate)
values (''2012-06-18T10:34:09'')'
print 'Testing ' + #Alias
exec sp_executesql #sql
end try
begin catch
print 'Error in language ' + #Alias
print ERROR_MESSAGE()
end catch
end
select #LangID = min(langid)
from sys.syslanguages
where langid > #LangID
end
According to the String Literal Date and Time Formats section in Microsoft TechNet, the standard ANSI Standard SQL date format "YYYY-MM-DD hh:mm:ss" is supposed to be "multi-language". However, using the same query, the ANSI format does not work in all SQL languages.
For example, in Danish, you will many errors like the following:
Error in language Danish
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
If you want to build a query in C# to run on SQL Server, and you need to pass a date in the ISO 8601 format, use the Sortable "s" format specifier:
string.Format("select convert(datetime2, '{0:s}'", DateTime.Now);
Management studio creates scripts like:
insert table1 (foodate) values(CAST(N'2012-06-18 10:34:09.000' AS DateTime))
you need to add it like
insert into table1(date1) values('12-mar-2013');
No need to use convert. Simply list it as a quoted date in ISO 8601 format.
Like so:
select * from table1 where somedate between '2000/01/01' and '2099/12/31'
The separator needs to be a / and it needs to be surrounded by single ' quotes.
If you are storing values via any programming language
Here is an example in C#
To store date you have to convert it first and then store it
insert table1 (foodate)
values (FooDate.ToString("MM/dd/yyyy"));
FooDate is datetime variable which contains your date in your format.
I encounter into a more generic problem: getting different (and not necessarily known) datetime formats and insert them into datetime column. I've solved it using this statement, which was finally became a scalar function (relevant for ODBC canonical, american, ANSI and british\franch date style - can be expanded):
insert into <tableName>(<dateTime column>) values(coalesce
(TRY_CONVERT(datetime, <DateString, 121), TRY_CONVERT(datetime, <DateString>,
101), TRY_CONVERT(datetime, <DateString>, 102), TRY_CONVERT(datetime,
<DateString>, 103)))
If the format of the date is as follows in sql : (datetime,null)
1
You can also use the "CAST" keyword
(CAST('2015-12-25 15:32:06.427' AS DateTime))
Just make sure that the date is in the correct format
I need your help in small problem, I have a column (data type timestamp) in SQL Server 2008.
Now I want to show this timestamp value in ASP.Net C# app as string. Is there any way to do that?
I tried it using regular data fetching in ASP.Net but it produced System.byte[] as output rather than actual value. In SQL Server Management Studio values are represented as 0x000000000000B3C0.
One option is to change it to the Date, while getting from the database. Like:
SELECT timestamp = DATEDIFF(s, '19700101', yourTimestampColumn)
FROM yourTable
I don't know if i catch you, but in sql you can cast timestamp value to datetime then to varchar like this:
declare #val timestamp = 0x0000AAE200B29565
select cast(cast(#val as datetime) as varchar(max))