How to convert Oracle to Sql server (SSM)? - sql

Here is the Query
SELECT REGEXP_REPLACE (F.COUNTRY,
'null',
NULL,
1,
0,
'i') COUNTRY from Table
I need to convert the above oracle query to sql query (SSM).

Something like this?
CREATE TABLE #str
(
nstr NVARCHAR(200)
);
INSERT INTO #str VALUES('abc 123');
INSERT INTO #str VALUES('null');
INSERT INTO #str VALUES('Value ''null'' is NULL');
INSERT INTO #str VALUES('Null');
INSERT INTO #str VALUES('NULL');
-- general, first instance
SELECT nstr, STUFF(nstr, CHARINDEX('null', nstr), LEN('null'), 'NULL') FROM #str
-- ofc if you are strictly replacing the string 'null' with NULL, you don't need regular expression
SELECT nstr, new_nstr = (CASE WHEN nstr = 'null' THEN NULL ELSE nstr END) FROM #str
-- replace won't work
SELECT nstr, replace_nstr = replace(nstr, 'null', NULL) FROM #str

Related

SQL Sever 2016 - Inconsistent Behavior - The argument 2 of the "JSON_VALUE or JSON_QUERY" must be a string literal

We are using SQL Server 2016 and I wrote a function that uses the following code:
IF #JsonString IS NULL OR LTRIM(RTRIM(#JsonString)) = ''
BEGIN
RETURN NULL;
END
DECLARE #ArrayValues VARCHAR(100);
SELECT #ArrayValues = REPLACE(REPLACE(REPLACE(
JSON_QUERY(#JsonString, #JsonPathToArray)
,'"', ''), '[', ''), ']', '');
RETURN #ArrayValues;
Basically, I get the array and remove the delimiting characters.
I have 2 stored procedures that use this function. One works perfectly, the other does not.
Any ideas?
Explanations:
The documentation states, that you need SQL Server 2017+ to provide a ...variable as the value of path... and this is the explanation for the "The argument 2 of the "JSON_VALUE or JSON_QUERY" must be a string literal." error in your statement.
For SQL Server 2016 you may use OPENJSON():
DECLARE #ArrayValues VARCHAR(100)
DECLARE #JsonString VARCHAR(100) = '{"Key" :["a","b","c"]}'
DECLARE #JsonPathToArray VARCHAR(100) = '$.Key'
SELECT #ArrayValues = REPLACE(REPLACE(REPLACE(
JSON_QUERY([value])
,'"', ''), '[', ''), ']', '')
FROM OPENJSON(#JsonString)
WHERE CONCAT('$.', [key]) = #JsonPathToArray
SELECT #ArrayValues
Additional notes:
Note, that the statement from your current apporach replaces every occurrence of the ", [ and ] characters, even if these characters are part of the JSON values.
So, the statement from the question:
DECLARE #ArrayValues VARCHAR(100)
DECLARE #JsonString VARCHAR(100) = '{"Key" :["a","b","c","EscapedContent\"[]"]}'
DECLARE #JsonPathToArray VARCHAR(100) = '$.Key'
SELECT #ArrayValues = REPLACE(REPLACE(REPLACE(
JSON_QUERY(#JsonString, #JsonPathToArray)
,'"', ''), '[', ''), ']', '');
SELECT #ArrayValues
returns:
a,b,c,EscapedContent\
If you want to aggregate the items from one JSON array, you may try a different approach (again SQL Server 2017+ is needed):
DECLARE #ArrayValues VARCHAR(100)
DECLARE #JsonString VARCHAR(100) = '{"Key" :["a","b","c", "EscapedContent\"[]"]}'
DECLARE #JsonPathToArray VARCHAR(100) = '$.Key'
SELECT #ArrayValues = STRING_AGG([value], ',') WITHIN GROUP (ORDER BY CONVERT(int, [key]))
FROm OPENJSON(#JsonString, #JsonPathToArray)
SELECT #ArrayValues
Result:
a,b,c,EscapedContent"[]

T SQL Remove ASCII character from SELECT

I'm using SQL Server 2014.
I have the below SQL statement to find unmatched records. However, it is now working correctly as the field 'dsc' in the OPENQUERY actually contains a horizontal tab (ASCII char 009) before the string values:
SELECT [E_Code]
FROM [Person] P
WHERE P.E_Code NOT IN (
SELECT dsc
FROM OPENQUERY(svr01, 'select "dsc" from TST.eth')
)
How do I remove ASCII char 009 from the dsc field? I have tried LTRIM to no avail.
Thanks.
DECLARE #str VARCHAR(20) = CONCAT('This is a tab--> ', '<--');
SELECT #str, REPLACE(#str, CHAR(9), '');
SELECT [E_Code]
FROM [Person] P
WHERE P.E_Code NOT IN (
SELECT REPLACE(dsc, CHAR(9), '')
FROM OPENQUERY(svr01, 'select "dsc" from TST.eth')
)
Alter max recursion and create the following
Create Function dbo.ASCIICleaner(#inputstring nvarchar(max))
Returns nvarchar(max)
BEGIN
Declare #returnValue nvarchar(max) = '';
with lengths as
(
select #inputstring data, len(#inputstring) length,1 start
)
,recurv as
(
select data,length,UNICODE(substring(data,start,1)) chari ,start from lengths where start= 1
union all
select data,length,UNICODE(substring(data,start+1,1)),start+1 from recurv where length > start
)
select #returnValue+= char(chari)
from recurv
where chari between 32 and 127
order by start asc
return #returnValue
END
select dbo.ASCIICleaner('aËbËcËDËEËF')
abcDEF will be returned

How to separate a string and insert into table?

My question is that I have a string like this
Red,House|White,Car|Blue,Table
and I want insert this elements in different rows like this
- Col1 Col2
- -----------
- Red House
- White Car
- Blue Table
How can I do it?
maybe this is what are you looking for.
SELECT Substring(value, 1,Charindex(',', value)-1) as col1
, Substring(value, Charindex(',', value)+1, LEN(value)) as col2
FROM STRING_SPLIT('Red,House|White,Car|Blue,Table', '|')
works since SQL Server 2016
You can try this query.
DECLARE #str VARCHAR(500) = 'Red,House|White,Car|Blue,Table'
CREATE TABLE #Temp (tDay VARCHAR(100))
WHILE LEN(#str) > 0
BEGIN
DECLARE #TDay VARCHAR(100)
IF CHARINDEX('|',#str) > 0
SET #TDay = SUBSTRING(#str,0,CHARINDEX('|',#str))
ELSE
BEGIN
SET #TDay = #str
SET #str = ''
END
INSERT INTO #Temp VALUES (#TDay)
SET #str = REPLACE(#str,#TDay + '|' , '')
END
SELECT *
FROM #temp
SELECT tday,
PARSENAME(REPLACE(tday,',','.'),2) 'Col1' ,
PARSENAME(REPLACE(tday,',','.'),1) 'Col2'
FROM #temp
You can check the live demo Here.
I go with using string_split() or a similar string splitter function which you can add to your database. However, I would phrase the final extract logic as:
select left(s.value, v.split - 1),
stuff(s.value, 1, v.split, '')
from string_split('Red,House|White,Car|Blue,Table', '|') s cross apply
(values (charindex(',', s.value))) v(split);

Function which takes a column values and convert it into a comma separated values

I want an SQL function which takes a result of a select statement as parameter and return a string of comma separated values for the result. If there is a NULL value then it should leave a space and continue with the result.
I tried using the COALESCE() expression, but this takes out the NULL values and returns only valid values.
declare #str varchar(MAX)
SELECT #str= coalesce(#str + ',', '')+ a.D8_BOOK_YEAR_END
FROM (select D8_BOOK_YEAR_END from CUST_PRODUCT_ACCOUNTS
WHERE CUST_PRODUCT_ID=1) a
print #str
For example: In the image, I need to pass the column NAME into the function and it should return me the values as Mango, ,Apple,Grape.
I want an SQL function which takes a result of a select statement as parameter and return a string of comma separated values for the result. If there is a null value then it should leave a space and continue with the result.
You can do that as
--Create a table (just for test)
CREATE TABLE T(
Str VARCHAR(45)
);
INSERT INTO T VALUES
('One'),
(NULL),
('Two'),
('Three');
-- Create a type
CREATE TYPE MyData AS TABLE (Str NVARCHAR(300));
-- Create the function
CREATE FUNCTION dbo.MyFunc(
#Data MyData READONLY
)
RETURNS NVARCHAR(300)
AS
BEGIN
DECLARE #Result NVARCHAR(300) = N'';
SELECT #Result = STUFF(
(
SELECT ',' + ISNULL(Str, '') --Or ' ' as you like
FROM #Data
FOR XML PATH('')
), 1, 1, ''
);
RETURN (#Result);
END
-- Finally, use it
DECLARE #Test MyData;
INSERT INTO #Test SELECT * FROM T;
SELECT dbo.MyFunc(#Test);
Returns:
+------------------+
| (No column name) |
+------------------+
| One,,Two,Three |
+------------------+
And here is a live demo
DECLARE #TABLE TABLE (
ID INT
,Info VARCHAR(MAX)
)
INSERT INTO #TABLE
VALUES (1,'mango')
INSERT INTO #TABLE
VALUES (1,'apple')
INSERT INTO #TABLE
VALUES (1,null)
INSERT INTO #TABLE
VALUES (1,'grape')
INSERT INTO #TABLE
VALUES (2,'mango1')
INSERT INTO #TABLE
VALUES (2,null)
INSERT INTO #TABLE
VALUES (2,null)
INSERT INTO #TABLE
VALUES (2,'grape1')
SELECT ID
,STUFF((
SELECT ',' + isnull(info, '')
FROM #TABLE T1
WHERE T1.id = T2.ID
FOR XML PATH('')
), 1, 1, '')
FROM #TABLE T2
GROUP BY ID
Use ISNULL(field,' ') somewhere to avoid the NULL value behavior.
You can use SQL Concatenation using XML PATH() method as illustrated with following sample query
SELECT
STUFF(
(
SELECT
',' + [user]
FROM dbo.UserCategoryValues
FOR XML PATH(''),TYPE
).value('.','VARCHAR(MAX)'
), 1, 1, ''
) As concatenated_string
This will take care of NULL values. Those NULLs will not be concatenated in to the list
But you can not wrap this code into a function as dynamic SQL that will take the field name and table name and build a SQL statement dynamically. SQL engine will throw an exception in that case

Convert SQL Server result set into string

I am getting the result in SQL Server as
SELECT StudentId FROM Student WHERE condition = xyz
I am getting the output like
StudentId
1236
7656
8990
........
The output parameter of the stored procedure is #studentId string and I want the return statement as
1236, 7656, 8990.
How can I convert the output in the single string?
I am returning single column [ie. StudentId]
Test this:
DECLARE #result NVARCHAR(MAX)
SELECT #result = STUFF(
( SELECT ',' + CONVERT(NVARCHAR(20), StudentId)
FROM Student
WHERE condition = abc
FOR xml path('')
)
, 1
, 1
, '')
DECLARE #result varchar(1000)
SELECT #result = ISNULL(#result, '') + StudentId + ',' FROM Student WHERE condition = xyz
select substring(#result, 0, len(#result) - 1) --trim extra "," at end
Use the COALESCE function:
DECLARE #StudentID VARCHAR(1000)
SELECT #StudentID = COALESCE(#StudentID + ',', '') + StudentID
FROM Student
WHERE StudentID IS NOT NULL and Condition='XYZ'
select #StudentID
Both answers are valid, but don't forget to initializate the value of the variable, by default is NULL and with T-SQL:
NULL + "Any text" => NULL
It's a very common mistake, don't forget it!
Also is good idea to use ISNULL function:
SELECT #result = #result + ISNULL(StudentId + ',', '') FROM Student
Use the CONCAT function to avoid conversion errors:
DECLARE #StudentID VARCHAR(1000)
SELECT #StudentID = CONCAT(COALESCE(#StudentID + ',', ''), StudentID)
FROM Student
WHERE StudentID IS NOT NULL and Condition='XYZ'
select #StudentID
The following is a solution for MySQL (not SQL Server), i couldn't easily find a solution to this on stackoverflow for mysql, so i figured maybe this could help someone...
ref: https://forums.mysql.com/read.php?10,285268,285286#msg-285286
original query...
SELECT StudentId FROM Student WHERE condition = xyz
original result set...
StudentId
1236
7656
8990
new query w/ concat...
SELECT group_concat(concat_ws(',', StudentId) separator '; ')
FROM Student
WHERE condition = xyz
concat string result set...
StudentId
1236; 7656; 8990
note: change the 'separator' to whatever you would like
GLHF!
This one works with NULL Values in Table and doesn't require substring operation at the end. COALESCE is not really well working with NULL values in table (if they will be there).
DECLARE #results VARCHAR(1000) = ''
SELECT #results = #results +
ISNULL(CASE WHEN LEN(#results) = 0 THEN '' ELSE ',' END + [StudentId], '')
FROM Student WHERE condition = xyz
select #results
The answer from brad.v is incorrect! It won't give you a concatenated string.
Here's the correct code, almost like brad.v's but with one important change:
DECLARE #results VarChar(1000)
SELECT #results = CASE
WHEN #results IS NULL THEN CONVERT( VarChar(20), [StudentId])
ELSE #results + ', ' + CONVERT( VarChar(20), [StudentId])
END
FROM Student WHERE condition = abc;
See the difference? :) brad.v please fix your answer, I can't do anything to correct it or comment on it 'cause my reputation here is zero. I guess I can remove mine after you fix yours. Thanks!
Use STRING_AGG:
SELECT STRING_AGG(sub.StudentId, ',') FROM
(select * from dbo.Students where Name = 'Test3') as sub
If you want to use e.g ORDER BY:
SELECT STRING_AGG(sub.StudentId, ',') WITHIN GROUP(Order by StudentId) FROM
(select * from dbo.Students where Name = 'Test3') as sub
or a single select statement...
DECLARE #results VarChar(1000)
SELECT #results = CASE
WHEN #results IS NULL THEN CONVERT( VarChar(20), [StudentId])
ELSE ', ' + CONVERT( VarChar(20), [StudentId])
END
FROM Student WHERE condition = abc;
Assign a value when declaring the variable.
DECLARE #result VARCHAR(1000) ='';
SELECT #result = CAST(StudentId AS VARCHAR) + ',' FROM Student WHERE condition = xyz