how to insert multiple values which is the output of a select query - sql

Select
cast(ltrim(rtrim(Substring(string,charindex('my',string)+len('my')+5,
charindex('for the company',string)-charindex('my',string)+len('my')-9))) as datetime)
from table
Select
cast(ltrim(rtrim(Substring(string,charindex('company',string)+len('company')+1,
len(String)-charindex('company',string)+len('company')-9)))as varchar)
from description
this 2 queries has a set of rows as output.
I want to insert these values to another table using single insert.
What i did is:
insert into table2(orderid,orderdate)
Select
cast(ltrim(rtrim(Substring(String, len('The order number')+1,
CHARINDEX ( 'as been created at', String) - len ('as been created at')))) as int)
,
cast(ltrim(rtrim(Substring(string,charindex('at',string)+len('at')+5,
charindex('for the company',string)-charindex('at',string)+len('at')-9))) as datetime)
from description
but its not inserted..its showing error like The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value..
Is there any another way to insert this?

when inserting a datetime you should specify a string that is SQL compliant i.e.
'YYYY-MM-DD HH:MM:SS'
I suspect that the CAST function cant convert the type specified. However you dont need to convert to a datetime, you can simply insert the string representation of the datetime.
Other issues you may encounter are the casting of ltrim(rtrim()) to an int. LTRIM, RTRIM both return a varchar. CHARINDEX already returns an int.
Ensure your types are consistent

To insert output from your two queries into a single table, the data types and number of columns from these queries should match with that of the table. You can use convert
CONVERT(
DATETIME,ltrim(rtrim(Substring(
string,charindex('at',string)+len('at')+5,
charindex('for the company',string)-charindex('at',string)+len('at')-9)))
,112)
for your datetime column and try (provided your target table has a datetime column for OrderDate).

Related

[Insert Destination [26]] Error: Column "GovtProgYN" cannot convert between unicode and non-unicode string data types

I am executing an ETL process and getting captioned error:
source datatype is char(1) and destination datatype is nchar(2)
How do I insert data from char to nchar?
Please help.
You don't say what platform you are using but you need to tell it to convert. Something like
SELECT CAST(GOVTPROGYN as NCHAR(2)) FROM TABLENAME_YOU_DID_NOT_SAY
or
SELECT CAST(GOVTPROGYN as CHAR(1)) FROM TABLENAME_YOU_DID_NOT_SAY
Per your title error, the n in nchar adds support for unicode, (same with nvarchar vs varchar). The data you are trying to insert is type char, but your destination field (GovtProgYN?) requires nchar.
Most SQL engines support a CAST function, which looks something like this: CAST( field AS datatype ). In your case, you would want to cast your insert value to nchar(2).
Example:
INSERT INTO Table ( GovtProgYN )
VALUES ( CAST ( #value AS nchar(2) )
Some SQL engines, like SQL Server, require you to designate unicode using the N prefix to a character string. If you are trying to manually insert a nchar value, use N'c' rather than 'c'.
Example:
INSERT INTO Table ( GovtProgYN )
VALUES ( N'c' )

Why does MS SQL Server error on inserting the second row but not on the first row?

I have an SQL table that will let me insert some rows with a datetime field but not all rows and I can't see why not. The error I get is
'The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.'
To try and work this out I created a temporary table with 1 colum and tried to add the two datetimes that are causing the issue.
create table #DateTimeTest ( created datetime );
I then try inserting these two rows
insert into dbo.#DateTimeTest (created) VALUES ('2020-06-12 05:46:00.00');
insert into dbo.#DateTimeTest (created) VALUES ('2020-06-19 05:31:00.00');
The first row is inserted without any problems, the second-row errors, but I can't understand why.
(1 row affected)
Msg 242, Level 16, State 3, Line 10
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.
Completion time: 2020-07-15T11:28:43.6451779+01:00
insert into dbo.#DateTimeTest (created) VALUES ('2020-06-19 05:31:00.00');
Apparently, your date format is YDM rather than YMD. You can fix this in several ways.
One method is to use an unambiguous date/time format. In your case, that would include a T:
insert into dbo.#DateTimeTest (created) VALUES ('2020-06-12T05:46:00.00');
insert into dbo.#DateTimeTest (created) VALUES ('2020-06-19T05:31:00.00');
The reason this works is because the YYYY-MM-DDTHH:MI:SS format is the standard format for a date/time format in SQL Server -- unambiguously and not affected by dateformat. Similarly YYYYMMDD (note: no hyphens) is the standard, unambiguous format for a date constant in SQL Server, but YYYY-MM-DD is subject to dateformat.
A second method would be to set the dateformat to YMD:
set dateformat YMD;
Here is a db<>fiddle illustrating this.
A third method would be to explicitly extract the datetime from the string, using a function such as convert() -- and perhaps a few string operations as well.

UPDATE SET FORMAT not working in SQL Server 2016?

FORMAT instruction works in a SELECT but has no effect in an UPDATE:
SELECT ##VERSION
DROP TABLE IF EXISTS #t;
CREATE TABLE #t(DateMin datetime);
INSERT INTO #t VALUES ('2019-13-01 00:00:00')
SELECT * FROM #t
UPDATE #t SET DateMin = FORMAT(DateMin, 'dd/MM/yyyy');
SELECT * FROM #t;
SELECT #DateMin AS a, FORMAT(#DateMin, 'dd/MM/yyyy') AS b
A type like DATETIME isn't stored with a format.
So if one updates a DATETIME with a string in a certain format, it doesn't matter for the stored value in the DATETIME field.
The formatted string is implicitly converted to a datetime. At least if it's in a format that's valid.
The function FORMAT, which returns a NVARCHAR is rather used for representation of the datetime field in a query.
Or if one wants to INSERT/UPDATE a string field with a datetime in a certain format. But that should be avoided, because it's much easier to work with a datetime than a string.
If you want to change that format for the user use this:
set dateformat dmy;
By running this statement:
DBCC USEROPTIONS;
you will see your dateformat is ydm so you can alway back it up to that if this is not what you wanted :)
You cannot set the output format of a datetime in the datetime itselfs.
If you need to output the datetime as formatted char/varchar, you need to use the convert-function when you select the data:
SELECT CONVERT(char(10), CURRENT_TIMESTAMP, 101) -- format: MM/dd/yyyy
SELECT CONVERT(char(10), CURRENT_TIMESTAMP, 103) -- format: dd/MM/yyyy
In your case:
SELECT #DateMin AS a, CONVERT(char(10), #DateMin, 103) AS b
That works as expected.
If you want to have a mutable data-type, you need to declare it as sql_variant:
DROP TABLE IF EXISTS #t;
CREATE TABLE #t(DateMin sql_variant);
INSERT INTO #t VALUES ('2019-01-13T00:00:00')
UPDATE #t SET DateMin = FORMAT(CAST(DateMin AS datetime), 'dd''/''MM''/''yyyy');
SELECT * FROM #t;
Also, your format-expression needs to explicitly put the / into quotation marks, aka 'dd''/''MM''/''yyyy', otherwise sql-server replaces it with the date-separator specific to the current culture, which would be . in my case.
Just use convert with option 103 instead, it works on all versions of sql-server and it's probably faster.
Also, your insert-statement fails on some versions of sql-server, because iso-date-format is 2019-01-13T00:00:00 and not 2019-13-01 00:00:00
Correct is:
INSERT INTO #t VALUES ('2019-01-13T00:00:00')
Also
DROP TABLE IF EXISTS #t;
is sql-server 2016+ only, otherwise you need
IF OBJECT_ID('tempdb..#t') IS NOT NULL DROP TABLE #t
And post sql-server 2005, you should use datetime2 instead of datetime.
You shouldn't use datetime anymore, because datetime uses float, and as such is imprecise - if you insert an iso datetime value, it can do funny things because of the float-point-machine-epsilon, e.g. set it to the next day if you have 23:59:59.999, just as a scary example.
I advise you to never use the sql_variant type. If you have a temp-table with defined columns, just create another column where you will write the char/varchar value to.

SQL Server: best way to insert "mm/dd/yyyy" into a "date" or "datatime2" column?

I have a bunch of values in the form of mm/dd/yyyy stored in a CSV. An example is 06/26/2017. What I found was that I could NOT insert it into a column declared as date or datetime2 type. What I CAN do is to modify that (empty) column to varchar first, then insert.
However at this point, after insertion as varchars, how can I convert this column to "date" or "datatime2"?
Attempting to set system-wide format doesn't work:
sql> SET DATEFORMAT 'mm/dd/yyyy'
[2019-03-31 09:42:04] [S0001][2741] SET DATEFORMAT date order 'mm/dd/yyyy' is invalid.
If the column's data type is date then convert the string to date with:
convert(date, '03/31/2019', 101)
and then insert it.
See the demo.
Read more about convert()
Edit:
Create a varchar column and a date column. Insert the values inside the varchar column and when the process finishes, update the date column by converting each value to a date, like:
UPDATE tablename
SET datecolumn = convert(date, varcharcolumn, 101)
After that you can remove the varchar column.

Converting Varchar into Date in data type

I am relatively new to SQL Server so I was wondering how to convert the data type from varchar to date format? I have a few thousands records so I need a query to help to convert the varchar to date in a single query.
I have the date in this format: yyyymmdd, in varchar(8) and I want to convert this into yyyymmdd, in date format.
Is there any queries to help me with this?
For various conversions between VARCHAR and DATETIME have a look at this link.
Actually in your case, since your VARCHAR is in yyyymmdd format, you could just:
convert(datetime, YourVarcharDateField, 112)
Simply Use this Inbuilt CONVERT Function, and Check this Link for formatting Dates
-- Use 101 if you have divider in your date
SELECT convert(datetime, '2014-01-02',101) as [DateTime]
-- Use 112 if you don't have divider in your date
SELECT convert(datetime, '20140131',112) as [DateTime]
Edited:
UPDATE yourTable SET field = convert(datetime, 'yourFieldName',112)
--This will update all of your field regardless of any particular row
--If you want to update any particular set of rows use `WHERE` clause
if you have more various formats goto to the given link.
Data types can be converted either implicitly or explicitly.
Implicit conversions are not visible to the user. SQL Server automatically converts the data from one data type to another. For example, when a smallint is compared to an int, the smallint is implicitly converted to int before the comparison proceeds.
Explicit conversions use the CAST or CONVERT functions.
The CAST and CONVERT functions convert a value (a local variable, a column, or another expression) from one data type to another
convert(datetime, '2013-05-04',101)
CAST ( expression AS data_type )
ALTER TABLE [dbo].[table] ADD ConvertedDate Date
UPDATE [dbo].[SysData] SET ConvertedDate = CAST(VarCharDate as Date)
ALTER TABLE [dbo].[table] DROP COLUMN VarCharDate
Use CAST OR CONVERT function to convert string to date
Try this:
SELECT CAST('20140102' AS DATE) AS convertedDate;
SELECT CAST(colName AS DATE) AS convertedDate FROM tableA; -- Replace column name and table name
OR
SELECT CONVERT(DATE, '20140102', 112) AS convertedDate;
SELECT CONVERT(DATE, colName, 112) AS convertedDate FROM tableA; -- Replace column name and table name
OUTPUT of both queries:
|convertedDate|
|-------------|
|2014-01-02 |
In SQL SERVER, there are two types of built in conversion techniques.
Convert
Cast
Convert having its own defaults so it will be outdated in upgraded version of SQL SERVER
better make use of CAST Conversion technique
In your scenario.Already having the date with datatype of Varchar(8) trying to Convert into Date
Solve in systematic manner.
Adding the one new Column in the existing table.
Alter Table Table_name Add changedDataTypeDate Date
Update the values in varchar datatype to Date Datatype
UpDate Table_name Set ChangedDataTypeDate = CAST(OriginalDataTypeDate as Date)
Again change the new column name into old column name.
Sp_Rename 'Tablename.changedDataTypeDate','OriginalDataTypeDate','COLUMN'
Its done.
Based on u r requirement.
Alter Table customer Add Purchase_Changedtype Date
Update Customer set Purchase_changedtype = CAST(Purchase_date as Date)
(If u need Time also replace Datetime istead of Date)
Alter table Customer Drop column Purchase_date
Sp_Rename 'Customer.Purchase_ChangedType','Purchase_Date','Column'