Convert string to datetime in SQL Server 2012 - tsql

I have a below requirement.
I want to insert records into a table using a stored procedure with below parameters
CREATE TABLE Mytable (MyPassword VARCHAR(10),PasswordDateTime DateTime)
My stored procedure is as follows to insert data into the above table.
CREATE PROCEDURE [dbo].[spPassword_Insert]
-- Parameters
#Password VARCHAR(200)
,#PasswordDateTime VARCHAR(20)
AS
SELECT #PasswordDateTime = CAST(#PasswordDateTime AS DATETIME)
INSERT INTO Mytable
SELECT #Password,#PasswordDateTime
I get the value of #PasswordDatetime from stored procedure as '2020-01-13 12:19:43.02'
I am getting the #PasswordDateTime value as string from the stored procedure and I want to convert the value data type as Date-time as per table definition without changing the value format.I want to insert the value as it is but the data type is to be changed.
While I am trying to convert a #PasswordDateTime value into date-time format, I am getting Conversion failed when converting date and/or time from character string error.
Please suggest how to convert this.

I got the answer.
DECLARE #PasswordDateTime VARCHAR(50)='2015-12-02 20:40:37.8130000'
SELECT #PasswordDateTime =cast(#PasswordDateTime as datetime2(2))
SELECT #PasswordDateTime
Thanks

Related

Postgres converting date formats on insert using trigger

I have a script that will insert data into a postgres table the issue is the data has a date format of DD/MM/YYYY and this date style Isn't accepted - I cant change the date style as that only lasts a session ( is what I read). I have this function and trigger to change the date format but I get the error date/time field value out of range: "DD/MM/YYY"
could anyone help on what is wrong with the function/trigger to get the date format to work I've tried a few iterations of this and all give the same error
CREATE OR REPLACE FUNCTION format_date()
RETURNS TRIGGER
LANGUAGE plpgsql
AS
$$
BEGIN
NEW.Invoice_Date = to_char(NEW.Invoice_Date, 'YYYY-MM-DD')::date;
NEW.Due_Date = to_char(NEW.Due_Date, 'YYYY-MM-DD')::date;
NEW.Paid_Date = to_char(NEW.Paid_Date, 'YYYY-MM-DD')::date;
RETURN NEW ;
END;
$$
CREATE TRIGGER format_date
BEFORE INSERT ON table_name
FOR EACH ROW
EXECUTE PROCEDURE format_date();
I've tried with to_date with and without the new. within the to_char and I've tried forcing it to date with ::date on the column. Any help will be much appreciated

Inserting data in SQL Server table not showing error on both condition

I have use procedure to insert data into table for fixed column size. But data trim and inserted successfully without any error.
I have lost some content from that variable.
This code snippet is not showing any error:
declare #temp varchar(5)
declare #tm table (a varchar(5))
set #temp ='abcdefghijkl'
insert into #tm
values(#temp)
select * from #tm
But this code snippet is showing this error:
String or binary data would be truncated
declare #temp1 varchar(5)
declare #tm1 table (a varchar(5))
insert into #tm1
values('abcdefghijkl')
select * from #tm1
The fact that the second code snippet is raising an error is a good thing.
It prevents you from corrupting data by mistake.
In the first code snippet, however, SQL Server will silently trim the string due to implicit conversion rules.
Whenever you attempt to populate a variable with a data that has a different data type, SQL Server will attempt to implicitly convert the data type to the data type of the variable.
This is well documented in the Converting Character Data section of the char and varchar (Transact-SQL) page:
When character expressions are converted to a character data type of a different size, values that are too long for the new data type are truncated.
This does not happen when inserting into a table, providing ANSI_WARNINGS is set to ON (which is the default state).
When ANSI_WARNINGS is set to ON, you get the
String or binary data would be truncated
error message.
When it's set to OFF, however, the implicit conversion will silently truncate the data:
set ansi_warnings off;
declare #temp1 varchar(5)
declare #tm1 table (a varchar(5))
insert into #tm1
values('abcdefghijkl')
select * from #tm1
Result:
a
abcde
Note: The ansi_warnings state does not have effect the implicit conversion when setting a variable value - it will always be truncated regardless of the ansi_warnings state.

PostgreSQL create index on cast from string to date

I'm trying to create an index on the cast of a varchar column to date. I'm doing something like this:
CREATE INDEX date_index ON table_name (CAST(varchar_column AS DATE));
I'm getting the error: functions in index expression must be marked IMMUTABLE But I don't get why, the cast to date doesn't depends on the timezone or something like that (which makes a cast to timestamp with time zone give this error).
Any help?
Your first error was to store a date as a varchar column. You should not do that.
The proper fix for your problem is to convert the column to a real date column.
Now I'm pretty sure the answer to that statement is "I didn't design the database and I cannot change it", so here is a workaround:
CAST and to_char() are not immutable because they can return different values for the same input value depending on the current session's settings.
If you know you have a consistent format of all values in the table (which - if you had - would mean you can convert the column to a real date column) then you can create your own function that converts a varchar to a date and is marked as immutable.
create or replace function fix_bad_datatype(the_date varchar)
returns date
language sql
immutable
as
$body$
select to_date(the_date, 'yyyy-mm-dd');
$body$
ROWS 1
/
With that definition you can create an index on the expression:
CREATE INDEX date_index ON table_name (fix_bad_datatype(varchar_column));
But you have to use exactly that function call in your query so that Postgres uses it:
select *
from foo
where fix_bad_datatype(varchar_column) < current_date;
Note that this approach will fail badly if you have just one "illegal" value in your varchar column. The only sensible solution is to store dates as dates,
Please provide the database version, table ddl, and some example data.
Would making your own immutable function do what you want, like this? Also look into creating a new cast in the docs and see if that does anything for you.
create table emp2 (emp2_id integer, hire_date VARCHAR(100));
insert into emp2(hire_date)
select now();
select cast(hire_date as DATE)
from emp2
CREATE FUNCTION my_date_cast(VARCHAR) RETURNS DATE
AS 'select cast($1 as DATE)'
LANGUAGE SQL
IMMUTABLE
RETURNS NULL ON NULL INPUT;
CREATE INDEX idx_emp2_hire_date ON emp2 (my_date_cast(hire_date));

Getting Postgres to truncate values if necessary?

If I create a table mytable with column data as varchar(2) and then insert something like '123' into the column, postgres will give me an error for Value too long for type.
How can I have Postgres ignore this and truncate the value if necessary?
Also, I do not (when creating the query) know the actual size of the data column in mytable so I can't just cast it.
According to the postgres documentation, you have to explicitly cast it to achieve this behavior, as returning an error is a requirement of the SQL standard. Is there no way to inspect the table's schema before creating the query to know what to cast it to?
Use text type with trigger instead:
create table mytable (
data text
);
create or replace function mytable_data_trunc_trigger()
returns trigger language plpgsql volatile as $$
begin
NEW.data = substring(NEW.data for 2);
return NEW;
end;
$$;
create trigger mytable_data_truncate_trigger
before insert or update on mytable for each row
execute procedure mytable_data_trunc_trigger();
insert into mytable values (NULL),('1'),('12'),('123');
select * from mytable;
data
------
1
12
12
(4 rows)
Easiest is just substring
INSERT INTO mytable (data) VALUES (substring('123' from 1 for 2));
You could change the datatype to varchar, and then use a trigger to enforce the two char constraint.

How to insert JPEG into a SQL Server 2000 database field of image type using Transact SQL

I'm trying to figure out how to insert a .JPG file into a SQL Server 2000 database field of type image using Transact SQL. Thanks.
Use OPENROWSET:
INSERT MyTable (ImageColumnName)
SELECT BulkColumn FROM OPENROWSET (BULK 'c:\myjpeg.jpg', SINGLE_BLOB) AS X
EDITED Whoops, you're using 2000--the previous solution is not supported. You have to use WRITETEXT:
CREATE TABLE MyTable
(
ID INT PRIMARY KEY IDENTITY (1,1),
ImageColumnName IMAGE NULL
)
GO
-- must insert a dummy value into the image column for TEXTPTR
-- to work in next bit
DECLARE #RowId INT
INSERT MyTable (ImageColumnName) VALUES (0xFFFFFFFF)
SELECT #RowId = SCOPE_IDENTITY()
-- get a pointer value to the row+column you want to
-- write the image to
DECLARE #Pointer_Value varbinary(16)
SELECT #Pointer_Value = TEXTPTR(ImageColumnName)
FROM MyTable
WHERE Id = #RowId
-- write the image to the row+column pointer
WRITETEXT MyTable.ImageColumnName #Pointer_Value 'c:\myjpeg.jpg'
There is a tool called textcopy.exe
You can find it under MSSQL\Binn or get it with SQL Server 2000 SP4
Alexander Chigrik wrote a nice stored procedure for usinig it with SQL query:
http://www.mssqlcity.com/Articles/KnowHow/Textcopy.htm
The stored procedure found in this tutorial worked for me:
Brief tutorial on text, ntext, and image