How to convert SQL Server timestamp object to string - c#

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))

Related

Stored procedure adds time to date format

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.

Fetching date in SQL Server 2008

How to split date in select query of SQL Server 2008 ?
If you feed you feed current date in database and the type of that column in database is date time then It will store the date as well as time.If any one want to fetch only the date part from that column then what can he do.
I can use this query but it should not work.
SELECT DonorName, DATE(DateOfDonation) AS DateOfDonation
FROM CreateDonorDetail;
it give error-
'DATE' is not a recognized built-in function name.
SQL Server 2008 has a DATE datatype - but it's disabled if your database was upgraded from a SQL Server 2005, and you didn't change the database compatibility level.
Check your compatibility level like this:
SELECT name, compatibility_level
FROM sys.databases
WHERE name = '-Your-database-name-here-'
If this compatibility level is 90, it's set to SQL Server 2005 and you won't be able to use DATE. Update your compatibility level to 100:
ALTER DATABASE AdventureWorks2012
SET COMPATIBILITY_LEVEL = 100
Now you should be able to use DATE:
SELECT
DonorName,
CAST(DateOfDonation AS DATE) AS DateOfDonation
FROM CreateDonorDetail;
Cast as Date type:
SELECT DonorName, Cast(DateOfDonation as Date) AS DateOfDonation
FROM CreateDonorDetail;
Prior to SQL Server 2008 you colud use something like this:
SELECT DonorName, CAST(FLOOR(CAST(DateOfDonation AS FLOAT)) AS datetime) AS DateOfDonation FROM CreateDonorDetail
DECLARE #DateTime DATETIME
SELECT #DateTime = '2010/05/20 11:21:13'
SELECT CONVERT(VARCHAR(10),#DateTime ,105) AS Date
the result will be in dd-mm-yyyy format (105)
Hope it will helps
mark as answer if it helped

How do I automatically get date when I create a new row in my SQL table?

I am doing a project in school, I have to create a website tool for salesmen to fill what they have done during the day, i.e. amount of quotes, quote sum, orders, order sum etc. I am using Visual Studio 2010, ASP.NET with C# with a SQL database.
I have to create a table with different columns, that I know how. But what I need is to have a column called Date and it has the datatype date. I need it to be filled automatically without having to input it manually. The same date that the new information was added. I have searched for solution in google and other places but I think I am searching with the wrong keywords, hopefully you can help me.
The format I wish for the date to be is DD-MM-YYYY
When you look for SQL default date on Google, the second result you get is this one.
In there, you have a default date example:
CREATE TABLE Orders
(
O_Id int NOT NULL,
OrderNo int NOT NULL,
P_Id int,
OrderDate date DEFAULT GETDATE()
)
using the DEFAULT keyword.
Create a sql datetime column in the database, and specify a default value of GetDate() or GetUtcDate() depending on which you want. Format is irrelevant on the input side; you will have to use a formatter on the select side (or in your c# code).
You can set the default value for the column as current date time..
create table tblname (
fieldname datetime default getdate()
)
Also see this question
Add default value of datetime field in SQL Server to a timestamp
You can use one of this to insert in the table instead.
String s = System.DateTime.Now.ToString("dd.MM.yyyy");
DateTime now = System.DateTime.Now;
The second one would be your choice because the type specified in yur table is Date.
If don't want to be setting it from the app, specify which database you are using to get a specific answer.

Getting DB Server DateTime in application

I am using Entity framework and have 1 field in database AddedDate that is DateTime and not null, so I need to pass DateTime value.
But the problem is I have to pass DB Server datetime. How can I manage in this sceario or how can I get DB Server datatime to pass this.
I need to some unique solution, because I am this on many forms.
Edit: I need DB server Datetime upon insertion/updation in my application so that I can pass to entity framework object.
Thanks
Since you are using entity framework, you can do something like this:
var dateQuery = yourDbContext.CreateQuery<DateTime>("CurrentDateTime() ");
DateTime dateFromSql = dateQuery .AsEnumerable().First();
In general, if you use the entity framework and you use DateTime in a field, it will automatically do the back/forth conversion for you, just the same way it does so for integers, doubles etc.
Unless you mean something special, i.e., a char[40] field that must be filled with a DateTime value of a particular format.
You can get database server date and time by running SELECT GETDATE()) script.
Consider you have a table with 4 colums - the first 3 being strings and the last datetime, You can solve your issue by issueing INSERT SQL like this:
INSERT INTO myTable VALUES ('x', 'y', 'z', SELECT GETDATE())
Can't you use a stored procedure so you can get DB server Datetime very easily.
Just use getdate() in your query. For example:
INSERT INTO your_table (AddedDate, ...other columns) VALUES (getdate(), ...other values)
This basically asks the server to insert its own current date into the field; there's no need for you to retrieve it locally.

SQL Server 2008 Datetime field overflow

I am using C# to interface with a SQL database. the database has a DateTime field. When I try to write a DateTime object from C#, I get the following error:
ERROR [22008] [Microsoft][ODBC SQL Server Driver]Datetime field overflow
I found this on the topic:
http://social.msdn.microsoft.com/forums/en-US/sqldataaccess/thread/ac1b5a6d-5e64-4603-9c92-b75ba4e51bf2/
Is there any manipulation I can do to my DateTime object on the C# side?
EDITS
I am trying to add DateTime.MinValue
Sounds like you are just passing in a bad date. For example, DateTime.MinValue is outside the accepted range for SQL Server datetime values by about 1600 years.
By the way, you shouldn't be using ODBC for C# to SQL Server communication. Using System.Data.SqlClient will give you much better performance.
The .NET DateTime object has a bigger range than the SQL date/time field.
In your data access layer, anytime your writing a date to the database, ensure that is inside the rate of SqlDateTime.MinValue and SqlDateTime.MaxValue.
I'm quiet sure, your .NET DateTime is not initialized, what means it is "0000-01-01" and this is not a valid value for SQL Server DATETIME and often not a desired value ;-)
Change all your datetime columns to datetime2 type. Generate the sql scripts using the query below.
select distinct concat('alter table ', table_name, ' alter column ', column_name, ' datetime2 ',
case when(is_nullable = 'NO') then ' NOT ' else '' end, ' NULL;')
from information_schema.columns where data_type = 'datetime';

Categories

Resources