How to store temp generated output in SQL into Table - sql

i have a sql statement, which the result of caclulations i want to write into a table.
i got an result for temp. But unluckily i cant transfer these results into a new table, because its saying that temp is not defined.
SELECT BUM.LMISTAT_import.UhrzeitBeginn, BUM.LMISTAT_import.UhrzeitEnde,BUM.LMISTAT_import.DatumEnde,BUM.LMISTAT_import.DatumBeginn,
TIMESTAMPDIFF(DAY, CAST(CONCAT(RIGHT(BUM.LMISTAT_import.DatumBeginn,2),'-',MID(BUM.LMISTAT_import.DatumBeginn,4,2),'-',LEFT(BUM.LMISTAT_import.DatumBeginn,2)) AS DATETIME),
CAST(CONCAT(RIGHT(BUM.LMISTAT_import.DatumEnde,2),'-',MID(BUM.LMISTAT_import.DatumEnde,4,2),'-',LEFT(BUM.LMISTAT_import.DatumEnde,2)) AS DATETIME)) AS temp
FROM BUM.LMISTAT_import;
INSERT INTO BUM.LMISTAT_import(BUM.LMISTAT_import.factor)
VALUES (temp)
;
actural SQL Result = "1054: Unknow column temp in field list";
the expected result is, that the table ..._import.factor is filled with values from temp.

Are you looking for create table as?
CREATE TABLE temp AS
SELECT i.UhrzeitBeginn, i.UhrzeitEnde,
i.DatumEnde, i.DatumBeginn,
TIMESTAMPDIFF(DAY,
CAST(CONCAT(RIGHT(i.DatumBeginn, 2), '-', MID(i.DatumBeginn,4,2), '-', LEFT(i.DatumBeginn,2)) AS DATETIME),
CAST(CONCAT(RIGHT(i.DatumEnde, 2), k'-', MID(i.DatumEnde, 4, 2), '-', LEFT(i.DatumEnde,2)) AS DATETIME)
) AS temp
FROM BUM.LMISTAT_import i;

You probably want SELECT...INTO.
In your first query, "AS temp" creates an alias for your result set, not a column list, which "VALUES (...)" requires, but which won't work anyway here.

Consider the syntax
INSERT INTO temp (a,b,c)
SELECT x,y,z ...;
Or even
CREATE TABLE temp (a,b,c)
SELECT x,y,z ...;
Try to go back into DatumBeginn and store it as a DATE that is yyyy-mm-dd, not some other form.
Failing that, use STR_TO_DATE() as a much more concise way to parse malformed date strings.
And a properly formed string does not need CAST( ... AS DATE)

Related

How to insert values into a postgres table using for loop?

I have a script like this in postgres
begin;
INSERT INTO "schema"."table"(price, different_table_foreign_key)
VALUES
(1, 1)
end;
for testing purposes I want to fill table 100 times with the same values as seen above.
how can I do this using a for loop?
No need for a loop, you can use generate_series() for that:
INSERT INTO "schema"."table"(price, different_table_foreign_key)
select 1,1
from generate_series(1,100);
If you want a different value for each row, just use the one returned by `generate_series()
INSERT INTO "schema"."table"(price, different_table_foreign_key)
select 1, g.value
from generate_series(1,100) as g(value)

Convert function SQL Server

I'm trying to convert the data of a column from varchar(255) to Timestamp.
I went to Microsoft documentation and it's not working
Code:
SELECT
["Data Nascimento"]
FROM
[leoninos] AS Original,
CONVERT(VARCHAR, ["Data Nascimento"]) AS VARCHAR,
CONVERT(timestamp(6, 4), ["Data Nascimento"]) AS timestamp;
Error:
Msg 156, Level 15, State 1, Line 53.
Incorrect syntax next to keyword 'CONVERT'.
What is the syntax error?
Thanks in advance.
Don't use varchar and timestamp as column aliases. Try this:
SELECT ["Data Nascimento"] as original
TRY_CONVERT(varchar(255), ["Data Nascimento"]) AS type_varchar
-- TRY_CONVERT(timestamp(6, 4), ["Data Nascimento"]) AS type_timestamp
FROM [leoninos] ;
Notes:
timestamp isn't really appropriate. I don't know what you are trying to do.
The FROM clause goes after the SELECT list.
Don't use SQL keywords as column names (even if they are not reserved).
Use try_convert() in case the conversion fails.
It's hard to tell what you are doing- but it appears that you are trying to select a table and also two scalars at once. Try just doing the CONVERT statements on their own with sample values:
SELECT CONVERT(int, '10'), CONVERT(date, '20180720')
Then, once you have it working for some sample values, you can convert column values:
CREATE TABLE #test (a NVARCHAR(max))
INSERT INTO #test VALUES ('january 1 2018')
INSERT INTO #test VALUES ('20180720')
SELECT a, CONVERT(date, a) FROM #test
DROP TABLE #test

Queries using temp tables

SELECT 1
FROM geo_locationInfoMajor_tbl
WHERE geo_locationInfoM_taluka IN(SELECT * from #temp
I have created a temp table which gets its values from the front end.. using a function I insert values into the temp table...
Now the data in the temp table is mixed... it can be integer or varchar..
when I pass only int or varchar into the temp table it is fine.
but if the output is mixed the query throws an error.. how to deal with this?
Conversion failed when converting the varchar value 'English' to data type int.
this is fine-->
#temp
1
this is not-->
1
English
How many values do you have in you temp table?
if you want to use the IN clause you should only use one column that is identical with your geo_locationInfoMajor_tbl.
try this:
SELECT * FROM geo_locationInfoMajor_tbl
WHERE geo_locationInfoM_taluka IN (SELECT geo_locationInfoM_taluka from #temp)

Using cast in insert statement

I am inserting some raw data into a table in MS SQL 2005 from excel.
Some of these data are not formatted correctly ie the amount colum is formatteT as a number 12345 whereas i need to be like 123.45 so i use this
CAST(TRANSACTION_HISTORY.AMOUNT AS decimal) / 100
to convert it correctly.
However is there a way to use the cast in an insert statement??
thanks
You can use CAST in any kind of statement(Insert, update, delete, select) where you use data.
Insert into table1 values( CAST(col1 as nvarchar(50)) )
I assume you're using a linked server or openquery to get the data from excel. You can cast in the select statement.
So
INSERT INTO YourTable
SELECT Cast(Transaction_History.Amount AS Decimal)/100
FROM EXCELLINK...[$Sheet1]
You could also just update all values in the table after you do the import
UPDATE YourTable
SET YourColumn = YourColumn/100

String manipulation SQL

I have a row of strings that are in the following format:
'Order was assigned to lastname,firsname'
I need to cut this string down into just the last and first name but it is always a different name for each record.
The 'Order was assigned to' part is always the same.......
Thanks
I am using SQL Server. It is multiple records with different names in each record.
In your specific case you can use something like:
SELECT SUBSTRING(str, 23) FROM table
However, this is not very scalable, should the format of your strings ever change.
If you are using an Oracle database, you would want to use SUBSTR instead.
Edit:
For databases where the third parameter is not optional, you could use SUBSTRING(str, 23, LEN(str))
Somebody would have to test to see if this is better or worse than subtraction, as in Martin Smith's solution but gives you the same result in the end.
In addition to the SUBSTRING methods, you could also use a REPLACE function. I don't know which would have better performance over millions of rows, although I suspect that it would be the SUBSTRING - especially if you were working with CHAR instead of VARCHAR.
SELECT REPLACE(my_column, 'Order was assigned to ', '')
For SQL Server
WITH testData AS
(
SELECT 'Order was assigned to lastname,firsname' as Col1 UNION ALL
SELECT 'Order was assigned to Bloggs, Jo' as Col1
)
SELECT SUBSTRING(Col1,23,LEN(Col1)-22) AS Name
from testData
Returns
Name
---------------------------------------
lastname,firsname
Bloggs, Jo
on MS SQL Server:
declare #str varchar(100) = 'Order was assigned to lastname,firsname'
declare #strLen1 int = DATALENGTH('Order was assigned to ')
declare #strLen2 int = len(#str)
select #strlen1, #strLen2, substring(#str,#strLen1,#strLen2),
RIGHT(#str, #strlen2-#strlen1)
I would require that a colon or some other delimiter be between the message and the name.
Then you could just search for the index of that character and know that anything after it was the data you need...
Example with format changing over time:
CREATE TABLE #Temp (OrderInfo NVARCHAR(MAX))
INSERT INTO #Temp VALUES ('Order was assigned to :Smith,Mary')
INSERT INTO #Temp VALUES ('Order was assigned to :Holmes,Larry')
INSERT INTO #Temp VALUES ('New Format over time :LootAt,Me')
SELECT SUBSTRING(OrderInfo, CHARINDEX(':',OrderInfo)+1, LEN(OrderInfo))
FROM #Temp
DROP TABLE #Temp