REGEXP_SUBSTR equivalent in SQL Server - sql-server

I have an Oracle query using
SELECT REGEXP_SUBSTR('500 Oracle Parkway, Redwood Shores, CA',',[^,]+,')
FROM DUAL;
It returns the output as below:
, Redwood Shores,
I am trying to get the exact same result in SQL Server. I tried to do it as below
substring(text, patindex, length)
But I struggled with length specification.
Can you please let me know how I can achieve this is in SQL Server?

You can try below query
WITH dual AS
(
SELECT '500 Oracle Parkway, Redwood Shores, CA' AS st
)
SELECT SUBSTRING(REVERSE(SUBSTRING(REVERSE(st),
CHARINDEX(',', REVERSE(st)),
LEN(st))),
CHARINDEX(',', st),
LEN(st)) str_value
FROM dual
Below is the result which I have got
Note: with clause is just for data preparation. Just make use of the substring part in select statement

Try this:
Declare #test varchar(max)='500 Oracle Parkway, Redwood Shores, CA'
select reverse(substring(reverse(substring(#test,charindex(',',#test),len(#test))),
charindex(',',reverse(substring(#test,charindex(',',#test),len(#test)))),
len(substring(#test,charindex(',',#test),len(#test)))))

Related

Achieve the same result from this postgresql query in SQL Server 2017

I have the following query that runs in postgresql-9.6, I need to achieve the same output on a SQL Server DB.
Here is the query, I've replaced all fields from my DB with the string values that would come from them anyway (DB Fields are: "primary_key_fields", "primary_key_values", "table_name", "min_sequence"):
SELECT
UNNEST(STRING_TO_ARRAY(demo.primary_key_fields, ',')) AS primary_key_fields,
UNNEST(STRING_TO_ARRAY(demo.primary_key_values, ',')) AS primary_key_values,
table_name,
min_sequence,
ROW_NUMBER() OVER(partition by demo.primary_key_fields) AS rn
FROM (
SELECT
'Name,surname,age,location,id' AS primary_key_fields,
'Nash,Marley,27,South Africa,121' AS primary_key_values,
'person' AS table_name,
'1' AS min_sequence
UNION ALL
SELECT
'Name,surname,age,location,id' AS primary_key_fields,
'Paul,Scott,25,South America,999' AS primary_key_values,
'person' AS table_name,
'1' AS min_sequence
) demo
I'm expecting the following output:
Highly appreciate the assistance. I'm using SQL Server 2017.
No longer needed. This question can be closed. No solution was found, changed the source system to accomdate what was needed.

SQL: what's an efficient way to turn data of money type into data with dollar format?

Using SQL Server 2008, how can I display data stored as varchar(25) as money?
Sample data sets:
36839.20000
4560.00000
Desired data:
$36,839.20
$4,560.00
What SQL statement can help us to achieve the above? Thanks.
Use format if it is sql server 2012 and above
declare #cur numeric(10,2) = 8.28
select format(#cur, 'C', 'en-us') as USCurrency
Please check CONVERT() function
For your case, you may use the following code,
SELECT '$' + CONVERT(VARCHAR(25),amt,1)
FROM yourtable

Need Help Converting Oracle Query to SQL Server

Several weeks ago I made a post to get help with converting a comma delimited list of values into a format that it could be used as part of an IN clause in Oracle. Here is a link to the post.
Oracle invalid number in clause
The answer was to split up the list into an individual row for each value. Here's the answer that I ended up using.
SELECT trim(regexp_substr(str, '[^,]+', 1, LEVEL)) str
FROM ( SELECT '1,2,3,4' str FROM dual )
CONNECT BY instr(str, ',', 1, LEVEL - 1) > 0
Is there a way that I can do something similar in SQL Server without having to create a custom function? I noticed that there's a STRING_SPLIT function, but I don't seem to have access to that on this SQL Server.
Any advice you might have would be greatly appreciated. I've been trying to take a stab at this for the majority of the day.
String_split function is available in MS SQL Server starting from version 2016. If you use older version you can write a few lines of code which do the same.
declare #str varchar(100)='1,2,3,4' --initial string
;with cte as (--build xml from the string
select cast('<s>'+replace(#str,',','</s><s>')+'</s>' as xml) x
)
--receive rows
select t.v.value('.[1]','int') value
from cte cross apply cte.x.nodes('s') t(v)

Using OPENQUERY with an Oracle database to query a date range

We have an Oracle database that we access through OpenQuery for some stuff. You apparently can't do date comparisons directly in OpenQuery using the OleDB driver, so to get around this you have to convert the dates to Julien dates and compare those numbers. I have the following query that we're trying to execute this in MS SQL Server (GPROD is a Linked Server via the OleDb driver):
SELECT *
FROM OPENQUERY(GPROD, '
SELECT *
FROM ORD_HDR_HST
WHERE (cast(to_number(to_char(SHIP_DATE ,''J'')) as numeric(10,0)) >= cast(to_number(to_char(to_date(''01-JAN-2015'') ,''J'')) as numeric(10,0)) AND
cast(to_number(to_char(SHIP_DATE ,''J'')) as numeric(10,0)) <= cast(to_number(to_char(to_date(''21-SEP-2015'') ,''J'')) as numeric(10,0)) )')
This query returns no results but also produces no error.
If I execute this query in Oracle SQL Developer, it works just fine and returns thousands of rows:
SELECT *
FROM ORD_HDR_HST
WHERE (cast(to_number(to_char(SHIP_DATE ,'J')) as numeric(10,0)) >= cast(to_number(to_char(to_date('01-JAN-2015') ,'J')) as numeric(10,0)) AND
cast(to_number(to_char(SHIP_DATE ,'J')) as numeric(10,0)) <= cast(to_number(to_char(to_date('21-SEP-2015') ,'J')) as numeric(10,0)) )
The SHIP_DATE field is of type DATE and is nullable, if that matters.
Does anyone know what I can do to get this working through OpenQuery?
Edit:
I did a test of the Julien Date conversion and there's definitely something fishy going on, but I don't know what's causing it. If I execute this in Oracle:
select cast(to_number(to_char(to_date('01-JAN-2015') ,'J')) as numeric(10,0)) from dual
I get 2457024
If I execute this on SQL Server:
select * from OPENQUERY(GPROD, 'select cast(to_number(to_char(to_date(''01-JAN-2015'') ,''J'')) as numeric(10,0)) from dual')
I get 1721443
I found a solution to the problem. By specifying a mask for the date, it will provide the proper results. Using:
to_char(to_date('01-JAN-2015','DD-MON-YYYY') ,'J')
instead of
to_char(to_date('01-JAN-2015') ,'J')
Gives the same result through OpenQuery and directly from Oracle.

How to produce JSON strings from SQL Server queries via TSQL?

I wanted to know if there is any function or something to convert the SQL select query result to JSON string format?
For example, SQL select query result is,
current target
-----------------
500 1000
1500 2000
JSON result:
[{"current":500,"target":1000},{"current":1500,"target":2000}]
Any ideas will be helpful.
Thanks.
SQL Fiddle
MS SQL Server 2008 Schema Setup:
Query 1:
DECLARE #TABLE TABLE ([current] INT, [target] INT)
INSERT INTO #TABLE VALUES
(500 , 1000),
(1500 , 2000)
SELECT '[' + STUFF((SELECT ',{"current":' + CAST([current] AS VARCHAR(30))
+ ',"target":' + CAST([target] AS VARCHAR(30)) + '}'
FROM #TABLE
FOR XML PATH(''),TYPE).value('.','NVARCHAR(MAX)'),1,1,'') + ']'
Results:
[{"current":500,"target":1000},{"current":1500,"target":2000}]
You don't specify version.
In SQL Server 2016 you will be able to do something like
SELECT [current],
target
FROM YourTable
ORDER BY [current]
FOR JSON AUTO;
More details here or in the official pre release documentation
I use
SELECT
JSON_QUERY(( SELECT
[current],target
FROM YourTable
FOR JSON PATH
))
Works well with minimal effort. I generally convert the output to a List<Dictionary<string,dynamic>> in C#/.Net (if I don't have an existing model).

Resources