Below is the variable in Oracle I need to convert in SQL Server please suggest.
V_BAD_EMAIL_CNT NUMBER := REGEXP_COUNT(pv_bad_emails,',') + 1;
This will return the number of comma's in the string + 1 in SQL
declare #pv_bad_emails varchar(1000);
set #pv_bad_emails = 'a,b,c,d';
select len(#pv_bad_emails) - len(replace(#pv_bad_emails, ',', '')) + 1
For more reference
How do you count the number of occurrences of a certain substring in a SQL varchar?
Related
I have a string like this:)
"<"FOSTIMON 75 M.J.>|4|4|4|3|3|3|3|3|3|3|3|3||||||||||||||||||||||||||||"
I need the sum of the numbers (4+4+4+3+...+3), expected result = 39
Thank you for the help!
THIS ANSWERS THE ORIGINAL QUESTION BEFORE EDITING.
Most databases support executing some form of prepared statement. In your case, probably the simplest method is to construct a SQL statement and then execute it dynamically.
The syntax for this varies dramatically from database to database. Out of randomness, I'm choosing SQL Server, but the functionality (although not the syntax) is available in almost any database:
declare #str nvarchar(max) = '|4|4|4|3|3|3|3|3|3|3|3|3||||||||||||||||||||||||||||';
set #str = 'select ' + replace(#str, '|', '+') + ' + 0';
exec sp_executesql #str;
Here is a rextester for this particular version.
Note that this works because + is a unary (numeric) operator, analogous to - but it does not change the sign.
Try this
Assuming the first part of the string upto the first "|" can be ignored
Not sure what version of SQL you're using but if its less than SQL2016 then use this string splitter
DECLARE #s NVARCHAR(50) = '<"FOSTIMON 75 M.J.>|4|4|4|3|3|3|3|3|3|3|3|3||||||||||||||||||||||||||||'
SELECT
SUM(CONVERT(INT, S.[Value]))
FROM dbo.DelimitedSplit8K(#s, '|') S
WHERE S.RN >= 2 AND S.RN <= 13
If you're on SQL2012 + then you can utilise TRY_PARSE and get rid of the WHERE clause altogether
SELECT
SUM(
CASE
WHEN TRY_PARSE(S.[Value] AS INT) IS NOT NULL
THEN CONVERT(INT, S.[Value])
ELSE 0
END
--CONVERT(INT, S.[Value])
)
FROM dbo.DelimitedSplit8K(#s, '|') S
If you're using SQL2016 + then use the inbuilt function, String_Split
SELECT
SUM(
CASE
WHEN TRY_PARSE(S.[Value] AS INT) IS NOT NULL
THEN CONVERT(INT, S.[Value])
ELSE 0
END
)
FROM STRING_SPLIT(#s, '|') S
From the following string value of session i will like to keep with only the part when the first number big or the last | beginning
session
nea|fact|za|ninja|web|14ff95092e3x1d214cd2
nea|fact|za|ninja|web|15001274f5ex323c9f96
nea|fact|za|ninja|web|1502897832ax418ecf1a
nea|fact|za|ninja|web|150399c1418x215f0e52
nea|fact|za|ninja|web|1503b3cdf02x386fc450
ta|fact|za|ninja|web|1503b3cdf02x386fc450
ta|fact|za|ninja|web|1503b3cdf02x386fc450
expected result
14ff95092e3x1d214cd2
15001274f5ex323c9f96
1502897832ax418ecf1a
150399c1418x215f0e52
1503b3cdf02x386fc450
1503b3cdf02x386fc450
1503b3cdf02x386fc450
if your db mysql then SUBSTRING_INDEX will help you
select SUBSTRING_INDEX(session, "|", -1);
Example:
select SUBSTRING_INDEX('nea|fact|za|ninja|web|14ff95092e3x1d214cd2', "|", -1);
returned: 14ff95092e3x1d214cd2
In mysql string related function
For Sql server your query will be
SELECT RIGHT(session , CHARINDEX ('|' ,REVERSE(session))-1)
In Oracle -
SELECT SUBSTR(session, '|', -1)
FROM TABLE_NAME;
For sql server:
declare #test varchar(1000) = 'nea|fact|za|ninja|web|14ff95092e3x1d214cd2'
SELECT RIGHT(#test , CHARINDEX ('|' ,REVERSE(#test))-1)
I got some dirty database of SQL to do a task. I have a column which can have data from different format like the following:
format 1 = 0000-0000000
format 2 = 0000.0000000
format 3 = 00000000000
The format 3 is a good format for my query.
$sql = "SELECT * from table where col='00000000000'"
I want to to remove these character in select query without disturbing the actual data.
Seems you need Replace function. Just remove extra symbols during comparison
SELECT * from table
where replace(replace(col, '-', ''), '.', '') ='00000000000'
There is a function to format the string:
create FUNCTION [dbo].[fn_StripString](#value as varchar(80), #KeepValues as varchar(80))
RETURNS varchar(80)
AS
begin
While PatIndex(#KeepValues, #value) > 0
Set #value = Stuff(#Valor, PatIndex(#KeepValues, #value), 1, '')
return #value
end
Then, assuming you just want numeric values:
SELECT *
from table
where dbo.fn_StripString(col, '%[^0-9]%') = '00000000000'
Use IN query
Select * from table where col in ('00000000000','0000.0000000','0000-0000000')
I was looking for a CONCAT function in SQL Server 2008 R2. I found the link for this function. But when I use this function, it gives the following error:
Msg 195, Level 15, State 10, Line 7
'CONCAT' is not a recognized built-in function name.
Does the CONCAT function exists in SQL Server 2008 R2?
If not, how do I concatenate strings in SQL Server 2008 R2?
Just for completeness - in SQL 2008 you would use the plus + operator to perform string concatenation.
Take a look at the MSDN reference with sample code. Starting with SQL 2012, you may wish to use the new CONCAT function.
CONCAT is new to SQL Server 2012. The link you gave makes this clear, it is not a function on Previous Versions, including 2008 R2.
That it is part of SQL Server 2012 can be seen in the document tree:
SQL Server 2012
Product Documentation
Books Online for SQL Server 2012
Database Engine
Transact-SQL Reference (Database Engine)
Built-in Functions (Transact-SQL)
String Functions (Transact-SQL)
EDIT Martin Smith helpfully points out that SQL Server provides an implementation of ODBC's CONCAT function.
I suggest you cast all columns before you concat them
cast('data1' as varchar) + cast('data2' as varchar) + cast('data3' as varchar)
This should work for you.
CONCAT, as stated, is not supported prior to SQL Server 2012. However you can concatenate simply using the + operator as suggested. But beware, this operator will throw an error if the first operand is a number since it thinks will be adding and not concatenating. To resolve this issue just add '' in front. For example
someNumber + 'someString' + .... + lastVariableToConcatenate
will raise an error BUT '' + someNumber + 'someString' + ...... will work just fine.
Also, if there are two numbers to be concatenated make sure you add a '' between them, like so
.... + someNumber + '' + someOtherNumber + .....
NULL safe drop in replacement approximations for SQL Server 2012 CONCAT function
SQL Server 2012:
SELECT CONCAT(data1, data2)
PRE SQL 2012 (Two Solutions):
SELECT {fn CONCAT(ISNULL(data1, ''), ISNULL(data2, ''))}
SELECT ISNULL(CAST(data1 AS varchar(MAX)), '') + ISNULL(CAST(data2 AS varchar(MAX)), '')
These two solutions collate several excellent answers and caveats raised by other posters including #Martin Smith, #Svish and #vasin1987.
These options add NULL to '' (empty string) casting for safe NULL handling while accounting for the varying behaviour of the + operator pertaining to specific operands.
Note the ODBC Scaler Function solution is limited to 2 arguments whereas the + operator approach is scalable to many arguments as needed.
Note also the potential issue identified by #Swifty regarding the default varchar size here remedied by varchar(MAX).
(city + ', ' + state + ' ' + zip) as ctstzip for select
(city + ', ' + state + ' ' + zip) for insert
Only cast or convert if any field type is different from others.
On insert the value needs to be in the correct spot you need it be inserted. Using "as" will give you an error.
i.e.
Insert into testtable (ctstzip) Values ((city + ', ' + state + ' ' + zip))
Yes the function is not in sql 2008. You can use the cast operation to do that.
For example we have employee table and you want name with applydate.
so you can use
Select cast(name as varchar) + cast(applydate as varchar) from employee
It will work where concat function is not working.
You can use '+' between the strings that you want to concat like
SELECT string1 + string2
If one of those give conversion error like if one of the columns is an int column you should cast it before concatenating the columns like
SELECT (CONVERT(nvarchar, intColumn) + string2
I have data in the following format in a sql server database table
[CPOID] [ContractPO] [ContractPOTitle]
1 10-SUP-CN-CNP-0001 Drytech
2 10-SUP-CN-CNP-0002 EC&M
I need to write a stored procedure to generate the following result
[CPOID] [ContractPO] [ContractPOTitle] [ConcatField]
1 10-SUP-CN-CNP-0001 Drytech CNP-0001-Drytech
2 10-SUP-CN-CNP-0002 EC&M CNP-0002-EC&M
where [ConcatField] generate the result using split the last two values of the [ContractPOTitle] column and combine with the [ContractPOTitle]
If the ContractPO field is always the same length, you could just do:
SELECT
CPOID,
ContractPO,
ContractPOTitle,
RIGHT(ContractPO, 8) + '-' + ContractPOTitle as [ConcatField]
FROM MyTable
Assuming that the length of the ContractPO field is not fixed AND we have to rely on stripping out the text after the next to last '-', the following SQL will work. It's a bit ugly, but these types of operations are necessary because there doesn't appear to be a LASTINDEX function available out of the box in SQL Server.
SELECT
CPOID,
ContractPO,
ContractPOTitle,
RIGHT(ContractPO, CHARINDEX('-', REVERSE(ContractPO), CHARINDEX('-', REVERSE(ContractPO)) + 1) - 1) + '-' + ContractPOTitle as [ConcatField]
FROM #myTable