Convert Oracle to_date('24-03-20','DD-MM-RR') to snowflake - snowflake-cloud-data-platform

I need your small help. I have to use to_date('24-03-20','DD-MM-RR') Oracle function in snowflake. Both output should be matching. Could anyone please help me.

Be careful with YY, as RR in Oracle behaved differently than Snowflake's YY. RR in Oracle basically made two digit years into a "closest to the year 2000" model, e.g. RR string of 49 gave you 2049, RR string of 51 gave you 1951.
If you need RR "functionality", see the reference to the TWO_DIGIT_CENTURY_START session parameter at this link:
https://docs.snowflake.com/en/sql-reference/functions-conversion.html#date-and-time-formats-in-conversion-functions
That parameter is further defined here:
https://docs.snowflake.com/en/sql-reference/parameters.html#label-two-digit-century-start
So, you could use YY, but you'll need to run an ALTER SESSION command before you execute your select, examples as follows:
ALTER SESSION SET TWO_DIGIT_CENTURY_START = 1970; --the default
SELECT to_date('24-03-20', 'DD-MM-YY'); --2020-03-24
ALTER SESSION SET TWO_DIGIT_CENTURY_START = 1900; --not what you want
SELECT to_date('24-03-20', 'DD-MM-YY'); --1920-03-24
ALTER SESSION SET TWO_DIGIT_CENTURY_START = 1950; --RR like
SELECT to_date('24-03-20', 'DD-MM-YY'); --2020-03-24
SELECT to_date('24-03-49', 'DD-MM-YY'); --2049-03-24
SELECT to_date('24-03-50', 'DD-MM-YY'); --1950-03-24
I hope this helps...Rich

Related

How to generate an excel file (.xlsx) from SQL Server

I have this query:
WITH InfoNeg AS
(
SELECT DISTINCT
n.idcliente,
CASE
WHEN DATEDIFF(MONTH, MAX(n.fechanegociacion), GETDATE()) <= 2
THEN 'Negociado 6 meses'
ELSE NULL
END AS TipoNeg
FROM
SAB2NewExports.dbo.negociaciones AS n
WHERE
Aprobacion = 'Si'
AND cerrado = 'Si'
GROUP BY
n.idcliente
), Multi AS
(
SELECT DISTINCT
idcliente, COUNT(distinct idportafolio) AS NumPorts
FROM
orangerefi.wfm.wf_master_HIST
WHERE
YEAR(Fecha_BKP) = 2021
AND MONTH(Fecha_BKP) = 08
GROUP BY
idcliente
)
SELECT DISTINCT
m.IdCliente, c.Nombre1
FROM
orangerefi.wfm.wf_master_HIST as m
LEFT JOIN
InfoNeg ON m.idcliente = InfoNeg.idcliente
LEFT JOIN
Multi ON m.IdCliente = Multi.idcliente
LEFT JOIN
SAB2NewExports.dbo.Clientes AS c ON m.IdCliente = c.IdCliente
WHERE
CanalTrabajo = 'Callcenter - Outbound' -- Cambiar aca
AND YEAR (Fecha_BKP) = 2021
AND MONTH(Fecha_BKP) = 08
AND GrupoTrabajo IN ('Alto') -- Cambiar aca
AND Bucket IN (1, 2) -- Cambiar aca
AND Multi.NumPorts > 1
AND Infoneg.TipoNeg IS NULL
When I run it, I get 30 thousand rows and the columns that I get when performing the query are: ClientID, name. I would like it to be saved in an Excel file when I run it, I don't know if it's possible.
Another question, is it possible to create a variable that stores text?
I used CONCAT(), but the text being so long is a bit cumbersome, I don't know if there is any alternative.
If you can help me, I appreciate it.
To declare a variable
DECLARE #string VARCHAR(MAX)
SET #string = concat()
then insert whatever you are concatenating
Here is an answer given by carusyte
Export SQL query data to Excel
I don't know if this is what you're looking for, but you can export the results to Excel like this:
In the results pane, click the top-left cell to highlight all the records, and then right-click the top-left cell and click "Save Results As". One of the export options is CSV.
You might give this a shot too:
INSERT INTO OPENROWSET
('Microsoft.Jet.OLEDB.4.0',
'Excel 8.0;Database=c:\Test.xls;','SELECT productid, price FROM dbo.product')
Lastly, you can look into using SSIS (replaced DTS) for data exports. Here is a link to a tutorial:
http://www.accelebrate.com/sql_training/ssis_2008_tutorial.htm
== Update #1 ==
To save the result as CSV file with column headers, one can follow the steps shown below:
Go to Tools->Options
Query Results->SQL Server->Results to Grid
Check “Include column headers when copying or saving results”
Click OK.
Note that the new settings won’t affect any existing Query tabs — you’ll need to open new ones and/or restart SSMS.

Why Hibernate HSQL Concat is not working for MSSQL?

So, I have Hibernate 5.3.1 in a project which connects to different enginees (MySql, Oracle, PostgreSQL and MS SQL), so I can't use native queries.
Let's say I have 3 records in a table, which all of them have the same datetime, but I need to group them only by date (not time). For example, 2019-12-04;
I execute this query:
SELECT
CONCAT(year(tx.date_), month(tx.date_), day(tx.date_)),
iss.code,
COUNT(tx.id)
FROM
tx_ tx
JOIN
issuer_ iss
ON
tx.id_issuer = iss.id
GROUP BY
CONCAT(year(tx.date_), month(tx.date_), day(tx.date_)), iss.code
But, when I test it connected to SQL SERVER 2017, instead of return 20191204, it's returning 2035. In Oracle and MySQL is working fine.
Anyone has any idea why is this happen? I've tried different ways, like use + instead of CONCAT but the result is the same.
I've also tried to extract them for separate (without concat), and they have been returning correct. The problem is, I need to group them by the complete date.
And just for the record, the field is declared as datetime2 in DDBB
How about simply adding them, instead of using CONCAT.
(year(tx.date_)*10000 + month(tx.date_)*100 + day(tx.date_)*1) AS datenum
Thus, try this:
SELECT
CAST((year(tx.date_)*10000 + month(tx.date_)*100 + day(tx.date_)*1) AS string) AS datenum,
iss.code
FROM tx_ tx
JOIN issuer_ iss
ON tx.id_issuer = iss.id
GROUP BY year(tx.date_), month(tx.date_), day(tx.date_), iss.code
Thanks for the hint Gert Arnold gave me. I just didn't realize that the query was adding like if they were numbers in MSSQL.
Finally, I manage to make it work in the 4 RDBMS casting to string first
SELECT
CONCAT(CAST(year(tx.date_) AS string), CAST(month(tx.date_) AS string), CAST(day(tx.date_) AS string)),
iss.code
FROM
tx_ tx
JOIN
issuer_ iss
ON
tx.id_issuer = iss.id
GROUP BY
CONCAT(year(tx.date_), month(tx.date_), day(tx.date_)), iss.code
I tried also casting to TEXT, but it throws exception in MySQL
Why use concat() to begin with?
Assuming Hibernate takes care of converting the non-standard year(), month() and day() functions, then the following should work on any DBMS
SELECT year(tx.date_), month(tx.date_), day(tx.date_), iss.code
FROM tx_ tx
JOIN issuer_ iss ON tx.id_issuer = iss.id
GROUP BY year(tx.date_), month(tx.date_), day(tx.date_), iss.code

How to determine who performed DROP/DELETE on Sql Server database objects?

There is always a need to find out details, either intentionally Or mistakenly someone executed DROP/DELETE command on any of following SQL Server database objects.
DROPPED - Table from your database
DROPPED - Stored Procedure from your database
DELETED - Rows from your database table
Q. Is there TSQL available to find db user who performed DELETE/DROP?
Q. What kind of permissions are needed for user to find out these details?
Did you check this ?
Right click on database.
Go to as shown in image :
Solution 2 :
This query gives alot of useful information for a database(apply filter as required) :
DECLARE #filename VARCHAR(255)
SELECT #FileName = SUBSTRING(path, 0, LEN(path)-CHARINDEX('\', REVERSE(path))+1) + '\Log.trc'
FROM sys.traces
WHERE is_default = 1;
SELECT gt.HostName,
gt.ApplicationName,
gt.NTUserName,
gt.NTDomainName,
gt.LoginName,
--gt.SPID,
-- gt.EventClass,
te.Name AS EventName,
--gt.EventSubClass,
-- gt.TEXTData,
gt.StartTime,
gt.EndTime,
gt.ObjectName,
gt.DatabaseName,
gt.FileName,
gt.IsSystem
FROM [fn_trace_gettable](#filename, DEFAULT) gt
JOIN sys.trace_events te ON gt.EventClass = te.trace_event_id
WHERE EventClass in (164) --AND gt.EventSubClass = 2
ORDER BY StartTime DESC;

list records from sql server UDF that returns Table in classic asp

I wrote my first sql Server returning table UDF since thought was better than using a SP
but, while can easily retrieve the result from sql server.. I can't get result calling it from classic ASP ADO
UDF is as follows:
CREATE FUNCTION dbo.udf_Alert
(
#I nvarchar (30),
#L nvarchar (10)
)
RETURNS TABLE AS RETURN
(
SELECT a.Message, a.Height, a.backgroundColor, a.isFree
from Advice a
join ActiveMessages b on b.MessageID=a.MessageID
join Items i on b.ItemID=i.ItemID
join Sellers s on i.UserID=s.UserID
join Users u on u.UID=s.UID
WHERE
(i.ItemID=#I and a.Active='1' and b.Active='1' and i.active='1' and i.Show='1' and CHARINDEX('ALERT',u.Modules)>0
and a.ValidFrom<GETDATE() and a.ValidTo>GETDATE() and u.PaidUntil>GETDATE() and charindex(#L,a.Languages)>-1 or charindex('all',a.Languages)>-1 )
UNION ALL
SELECT a.Message, a.Height, a.backgroundColor, a.isFree
FROM Advice a, Users u
WHERE u.isFree='1' and a.isFree='1' and (CHARINDEX(#L,a.Languages)>-1 or Charindex('all',a.Languages)>-1)
)
and I can easily execute from SSMS calling
Select * from dbo.udf_Alert('281F50246','fr')
But I have to embed into a classic ASP routine but I've not found the way to do it..
tried the SP method.. but I got error when try to set the parameters:
here what I tried:
sql="Select dbo.udf_Alert('xx','yy')"
dim cmdA
set cmdA = Server.CreateObject("ADODB.Command")
cmdA.ActiveConnection= cn
cmdA.CommandType=4
cmdA.CommandText=sql
cmda.Parameters.Append cmdA.CreateParameter("fd", nvarchar, adParamInput,30, itemID)
cmda.Parameters.Append cmdA.CreateParameter("fde", nvarchar, adParamInput,10, LanguageID)
' cmdA.Parameters("#I")=ItemID '<-----ERRROR HERE
' cmdA.Parameters("#L")=LanguageID
set rs=cmdA.Execute()
so I tried set Parametrs in other way.. but got same result:
ADODB.Command error '800a0bb9'
Arguments are of the wrong type, are out of acceptable range, or are in conflict with one another.
Can suggest some advice?
Thanks
Sergio
We tend to create stored procedure "wrappers" for UDFs on a one-to-one basis which can be called directly from web code. For your example, this might look like
CREATE PROCEDURE [dbo].[pr_Alert]
#I nvarchar (30),
#L nvarchar (10)
AS
SELECT * FROM testDb.dbo.udf_Alert(#I, #L)
RETURN
Your commandText would then be simply the name of the wrapper SP, "pr_Alert".
Hope this helps.

Update on linked server with nested subquery

I want to update on a linked server the result of a query as well from a linked server.
The first sql snippet gives me the value to be updated:
SELECT mmdb_vessel.IMONo, mmdb_vessel.DeathDate
From OPENQUERY(MMDB, 'SELECT FunctionalLocation, IMONo, VesselStatus, CONVERT(VARCHAR(10), DeathDate, 102) AS DeathDate
FROM VESSEL
WHERE VESSEL.VesselStatusID <> 42 AND VESSEL.DeathDate is not null') as mmdb_vessel
, eb_all_v
WHERE
eb_all_v.IMO_No = mmdb_vessel.IMONo
AND eb_all_v.status = 'in service'
the second is actually what I'm not able to implement, it should show what I want to achieve:
UPDATE EPI2..EPI.PLANT
SET KIND_OF_LIQUIDATION_NO = 1
, LIQUIDATION_DATE = [result from snippet above].DeathDate
Where EPI2..EPI.PLANT.IMONo = [result from snippet above].IMONo
I'm not so sure if my explanation is sufficient, please feel free to ask for additional information!
Thanks, already in advance,
Werner
I would recommend to select the data from the remote server first and store the required data e.g. in a temptable, because LinkedServer and updates can have some sideeffects (e.g. performing a tablescan on the remote table, altough you would not expect it if an updaet is involved, etc) - but this depends on your exact usage/scenario.
Select data you need to update
SELECT * INTO #tmpTable FROM LINKEDSERVER.EPI.dbo.PLANT WHERE ....
Perform the update on local server
UPDATE EPI2..EPI.PLANT SET KIND_OF_LIQUIDATION_NO = 1, LIQUIDATION_DATE = t.DeathDate FROM #tmpTable t INNER JOIN EPI2..EPI.PLANT p on t.IMONo = p.IMONo

Resources