How to ignore specific string value when using pattern and patindex function in SQL Server Query? - sql

I have this query here.
WITH Cte_Reverse
AS (
SELECT CASE PATINDEX('%[^0-9.- ]%', REVERSE(EmailName))
WHEN 0
THEN REVERSE(EmailName)
ELSE left(REVERSE(EmailName), PATINDEX('%[^0-9.- ]%', REVERSE(EmailName)) - 1)
END AS Platform_Campaign_ID,
EmailName
FROM [Arrakis].[xtemp].[Stage_SendJobs_Marketing]
)
SELECT REVERSE(Platform_Campaign_ID) AS Platform_Campaign_ID, EmailName
FROM Cte_Reverse
WHERE REVERSE(Platform_Campaign_ID) <> '2020'
AND REVERSE(Platform_Campaign_ID) <> ''
AND LEN(REVERSE(Platform_Campaign_ID)) = 4;
It is working for the most part, below is a screenshot of the result set.
The query I posted above extracts the 4 numbers to the right out of the initial value that is set for the column I am extracting out of. But I am unable to figure out how I can also have the query ignore cases when the right most value is -v2, -v1, etc. essentially anything with -v and whatever number version it is.

If you want four digits, then one method is:
select substring(emailname, patindex('%[0-9][0-9][0-9][0-9]%', emailname), 4)

Related

SQL CONCAT drops zeros from expression

I am trying different ways to put a 0 in front of month less than 10.
I tried the following expression but the 0 get dropped.
What am I doing wrong?
CASE
WHEN month([Transact_Date]) < 10
THEN CONCAT(str(0),STR(month([Transact_Date]),1))
ELSE month([Transact_Date])
END AS month_w_0
Thanks!
Tom
I think a left padding trick is what you want here. Assuming your database be SQL Server:
SELECT RIGHT('00' + STR(MONTH([Transact_Date])), 2) AS month_w_0
FROM yourTable;
You don't need a CASE expression for this. In more recent versions of SQL Server, the FORMAT function might also be able to handle this.
I have tested this and it returns the result you want:
select CASE WHEN mnt < 10 THEN
concat('0' , mnt)
ELSE mnt
END AS month_w_0
from ( select month([Transact_Date]) mnt
from test_t) A
I have realised what your problem is. YOu can do it this way too:
SELECT
CASE
WHEN month([Transact_Date]) < 10
THEN CONCAT(str(0),STR(month([Transact_Date]),1))
ELSE STR(month([Transact_Date]),1)
END AS month_w_0
from test_t
The problem is only the else part and I believe that is because case when clause returns only one type od data. In your then part you have tryed to retunr string and in the else part number.
Hope this helps...
Here is a demo

How to remove non alphanumeric characters in SQL without creating a function?

I'm trying to remove non alphanumeric characters in multiple columns in a table, and have no permission to create functions nor temporary functions. I'm wonder whether anyone here have any experiences removing non alphanumeric characters without creating any functions at all? Thanks. I'm using MS SQL Server Management Studio v17.9.1
If you have to use a single SELECT query like #Forty3 mentioned then the multiple REPLACEs like #Gordon-Linoff said is probably best (but definitely not ideal).
If you can update the data or use T-SQL, then you could do something like this from https://searchsqlserver.techtarget.com/tip/Replacing-non-alphanumeric-characters-in-strings-using-T-SQL:
while ##rowcount > 0
update user_list_original
set fname = replace(fname, substring(fname, patindex('%[^a-zA-Z ]%', fname), 1), '')
where patindex('%[^a-zA-Z ]%', fname) <> 0
Here is a starting point - you will need to adjust it to accommodate all of the columns which require cleansing:
;WITH allcharcte ( id, textcol1, textcol2, textcol1where, textcol2where )
AS (SELECT id,
CAST(textcol1 AS NVARCHAR(255)),
CAST(textcol2 AS NVARCHAR(255)),
-- Start the process of looking for non-alphanumeric chars in each
-- of the text columns. The returned value from PATINDEX is the position
-- of the non-alphanumeric char and is stored in the *where columns
-- of the CTE.
PATINDEX(N'%[^0-9A-Z]%', textcol1),
PATINDEX(N'%[^0-9A-Z]%', textcol2)
FROM #temp
UNION ALL
-- This is the recursive part. It works through the rows which have been
-- returned thus far processing them for use in the next iteration
SELECT prev.id,
-- If the *where column relevant for each of the columns is NOT NULL
-- and NOT ZERO, then use the STUFF command to replace the char
-- at that location with an empty string
CASE ISNULL(prev.textcol1where, 0)
WHEN 0 THEN CAST(prev.textcol1 AS NVARCHAR(255))
ELSE CAST(STUFF(prev.textcol1, prev.textcol1where, 1, N'') AS NVARCHAR(255))
END,
CASE ISNULL(prev.textcol2where, 0)
WHEN 0 THEN CAST(prev.textcol2 AS NVARCHAR(255))
ELSE CAST(STUFF(prev.textcol2, prev.textcol2where, 1, N'') AS NVARCHAR(255))
END,
-- We now check for the existence of the next non-alphanumeric
-- character AFTER we replace the most recent finding
ISNULL(PATINDEX(N'%[^0-9A-Z]%', STUFF(prev.textcol1, prev.textcol1where, 1, N'')), 0),
ISNULL(PATINDEX(N'%[^0-9A-Z]%', STUFF(prev.textcol2, prev.textcol2where, 1, N'')), 0)
FROM allcharcte prev
WHERE ISNULL(prev.textcol1where, 0) > 0
OR ISNULL(prev.textcol2where, 0) > 0)
SELECT *
FROM allcharcte
WHERE textcol1where = 0
AND textcol2where = 0
Essentially, it is a recursive CTE which will repeatedly replace any non-alphanumeric character (found via the PATINDEX(N'%[^0-9A-Z]%', <column>)) with an empty string (via the STUFF(<column>, <where>, N'')). By replicating the blocks, you should be able to adapt it to any number of columns.
EDIT: If you anticipate having more than 100 instances of non-alphanumeric characters to strip out of any one column, you will need to adjust the MAXRECURSION property ahead of the call.

How to fetch last character and increment it in sql

I have the following query
select case
when Right('BPUREN_3',1) Like '[A-Z]'
then concat('BPUREN','_1')
else
concat('BPUREN_3',right('BPUREN_3',1)+1)
End
I want output as BPUREN_4 But I am getting the result as BPUREN_34
select case
when Right('BPUREN_3',1) Like '[A-Z]' then 'BPUREN_1'
else concat(Left('BPUREN_3', 7),right('BPUREN_3',1)+1)
End
No need to concat('BPUREN','_1') it will always be 'BPUREN_1'
You could change Left('BPUREN_3', 7) to Left('BPUREN_3', LEN('BPUREN_3') - 1) if 'BPUREN_3' could change in length (for example if its a parameter in your real code)
concat('BPUREN_3', right('BPUREN_3', 1)+1) -- concat combines two strings together and returns a string. So you are combining BPUREN_3 with 4 (outputting the BPUREN_34). Instead change BUREN_3 toBPUREN_

Insert into sql Max +1 only numbers (prevent characters)

I'm using this code
(SELECT (MAX(CODE) +1 WHERE ISNUMERIC([code]) = 1)
I want to max +1 only my numbers of my column preventing characters characters.
NOTE: THIS QUESTION WAS TAGGED MYSQL WHEN THIS ANSWER WAS POSTED.
You can use substring_index() to split the values and then re-unite them:
(SELECT CONCAT(SUBSTRING_INDEX(MAX(Code), '-', 1), '-',
SUBSTRING_INDEX(MAX(CODE), '-', -1) + 1
)
FROM . . .
WHERE code LIKE '%NEW-1%'
)
This assumes that the wildcards do not have hyphens in them, and that the values after the "1" are all numbers.
Also, this doesn't pad the number is zeroes, but that is a good idea for such codes -- it ensures that they are always the same length and that they sort correctly.
The MAX() function accepts expressions, not just column names:
SELECT MAX(CASE ISNUMERIC(code) WHEN 1 THEN code END)+1 as next_code
FROM (
SELECT '15' AS code
UNION ALL SELECT ' 98 ' AS code
UNION ALL SELECT 'New-45' AS code
) foo
WHERE ISNUMERIC(code)=1;
16
(Link is to SQL Server 2005, docs for SQL Server 2000 are apparently no longer on line, but MAX() belongs to SQL standard anyway.)

TSQL - Remove Everything after the last period

I have a column string that may be one of the following.
10.0.2531.0
10.50.2500
10.0.2531.60
My requirement is, if there are 3 periods/decimal points, remove the last period/decimal and everything after that.
If I use the following, this will take care of the first row where there is only ".0", however, it does not work for the third row.
select
case
when right(column_1,2) = '.0' then left(column_1,len(column_1)-2)
else column_1 end,
FROM
table_1
I also tried the following but that didn't work.
select
case
when right(column_1,2) = '.' then left(column_1,len(column_1)-2)
when right(column_1,3) = '.' then left(column_1,len(column_1)-3)
else column_1 end,
FROM
table_1
The number after the third period/decimal may be a 0 or another number.
The following works, under the assumption that there are never five periods:
select (case when ip like '%.%.%.%'
then left(ip, len(ip) - charindex('.', reverse(ip))
else ip
end) as firstThree
Use a combination of charindex and substring.
SQL Fiddle
select reverse(substring(reverse(column_1), charindex('.',reverse(column_1))+1, len(column_1)))
from table_1
where len(column_1) - len(replace(column_1,'.','')) = 3