Search for ASCII values in sql server table - sql

I have table that one of the fields needs to be cleaned up. The basic table structure is as follows:
create table testComments(id int, comments text)
In the comments column some of the rows had to many "carriage returns" (char(13)) and "line feed" (char(10)). If there is more then one grouping per line I need to be able to modify it. The basic select statement that I have so far is a follows:
select count(id)
from testComments
where comments like('%' + char(13) + char(10) + char(13) + char(10) + '%')
This query will find the results
"This is a entry in the testComments crlf
crlf
In the comments field that works"
Although the query will not find the results if the comment is listed as follows:
"This is an entry in the testComments crlf
crlf
crlf
That will not work"
The query will only return a count of 1 entry for the above data. Any idea how I can change the query to return a count of 2?

Using the code you gave us, your query should work properly. So the details appear to be different, and I suspect that GolezTrol's comment is on the right track -- some of the CRLF pairs are really just solo CR or LF characters.
Try this:
select count(id)
from #testComments
where comments like('%' + char(13) + char(10) + char(13) + char(10) + '%')
or comments like('%' + char(10) + char(10) + '%')
or comments like('%' + char(13) + char(13) + '%')

The query will only return a count of 1 entry for the above data. Any idea how I can change the query to return a count of 2?
I think you're misunderstanding something basic.
The COUNT-Function returns the count of all returned rows. In your example it is still returning one row.
So no matter if you have this:
"This is an entry in the testComments crlf
crlf
That will not work"
Or this:
"This is an entry in the testComments crlf
crlf
crlf
crlf
crlf
That will not work"
COUNT will still return 1! (If you have one record that has this string)
EDIT: If you literally want to count the characters for each row, here you go:
SELECT LEN(REPLACE(myColumn, 'yourCharacter', '')) FROM ...

Try using a virtual table. I added up the differences in length of the comments field and the comments field after replacing the characters that you are looking for with empty strings.
SELECT SUM(DIF) FROM (
select
(
LEN(comments)
- LEN( REPLACE( REPLACE ( comments, char(13), ''),char(10),'') )
)
AS DIF
from #testComments
) as VT;

Related

SQL I need to extract a stored procedure name from a string

I am a bit new to this site but I have looked an many possible answers to my question but none of them has answered my need. I have a feeling it's a good challenge. Here it goes.
In one of our tables we list what is used to run a report this can mean that we can have a short EXEC [svr1].[dbo].[stored_procedure] or "...From svr1.dbo.stored_procedure...".
My goal is to get the stored procedure name out of this string (column). I have tried to get the string between '[' and ']' but that breaks when there are no brackets. I have been at this for a few days and just can't seem to find a solution.
Any assistance you can provide is greatly appreciated.
Thank you in advance for entertaining this question.
almostanexpert
Considering the ending character of your sample sentences is space, or your sentences end without trailing ( whether space or any other character other than given samples ), and assuming you have no other dots before samples, the following would be a clean way which uses substring(), len(), charindex() and replace() together :
with t(str) as
(
select '[svr1].[dbo].[stored_procedure]' union all
select 'before svr1.dbo.stored_procedure someting more' union all
select 'abc before svr1.dbo.stored_procedure'
), t2(str) as
(
select replace(replace(str,'[',''),']','') from t
), t3(str) as
(
select substring(str,charindex('.',str)+1,len(str)) from t2
)
select
substring(
str,
charindex('.',str)+1,
case
when charindex(' ',str) > 0 then
charindex(' ',str)
else
len(str)
end - charindex('.',str)
) as "Result String"
from t3;
Result String
----------------
stored_procedure
stored_procedure
stored_procedure
Demo
With the variability of inputs you seem to have we will need to plan for a few scenarios. The below code assumes that there will be exactly two '.' characters before the stored_procedure, and that [stored_procedure] will either end the string or be followed by a space if the string continues.
SELECT TRIM('[' FROM TRIM(']' FROM --Trim brackets from final result if they exist
SUBSTR(column || ' ', --substr(string, start_pos, length), Space added in case proc name is end of str
INSTR(column || ' ', '.', 1, 2)+1, --start_pos: find second '.' and start 1 char after
INSTR(column || ' ', ' ', INSTR(column || ' ', '.', 1, 2), 1)-(INSTR(column || ' ', '.', 1, 2)+1))
-- Len: start after 2nd '.' and go until first space (subtract 2nd '.' index to get "Length")
))FROM TABLE;
Working from the middle out we'll start with using the SUBSTR function and concatenating a space to the end of the original string. This allows us to use a space to find the end of the stored_procedure even if it is the last piece of the string.
Next to find our starting position, we use INSTR to search for the second instance of the '.' and start 1 position after.
For the length argument, we find the index of the first space after that second '.' and then subtract that '.' index.
From here we have either [stored_procedure] or stored_procedure. Running the TRIM functions for each bracket will remove them if they exist, and if not will just return the name of the procedure.
Sample inputs based on above description:
'EXEC [svr1].[dbo].[stored_procedure]'
'EXEC [svr1].[dbo].[stored_procedure] FROM TEST'
'svr1.dbo.stored_procedure'
Note: This code is written for Oracle SQL but can be translated to mySQL using similar functions.

How to hard code spaces at end of result?

I need to add spaces to the end of a column I have called NPI (nvarchar(20)). NPI is always 10 digits, but the requirements for the report want the first 10 digits to be the NPI followed by 10 spaces (text file formatting issues I assume). I have tried the following:
cast([NPI] as nvarchar(20)) + ' '
cast([NPI] as nvarchar(20)) + Space(10)
However, the result set does not change. It just shows the 10 digit NPI and spaces aren't included.
It sounds like you are actually using SQL Server instead of MySQL. VARCHAR() is for variable length strings and it will trim end whitespace. Cast instead to char/nchar for the desired output. It won't look like it in SSMS, so check datalength to confirm nchar(20) = 20 bytes * 2 for unicode.
SELECT CAST([NPI] AS NCHAR(20)) AS formattedNPI,
DATALENGTH(CAST([NPI] AS NCHAR(20))) AS confirmation
FROM your_table
This seems to work. The '*' is added to show that spaces are present..
print cast([NPI] as nchar(20)) + '*'
Here are a couple of other cheesy ways to add padding...
print substring([NPI] + ' ',1,20) + '*'
print [NPI] + space(20 - len([NPI])) + '*'
Add the space inside the cast
cast([NPI] + ' ' as nchar(20))
You're right #dfundako, I was fooled by my editor.
This works but I am using MariaDb (MySql) so it's maybe not relevant now.
select concat([NPI] , ' ')

Enter key issue in SQL

I have a column that is defined as a nvarchar(100).
Sometimes office users press enter key wrongly and it causes problems in some applications. When I check the value it seems like double space character in SQL Server. Now my mission is finding the records that has this situation. I tried the code below to find the problematic records:
DECLARE #NewLineChar AS CHAR(2) = CHAR(10) + CHAR(13);
SELECT *
FROM TBLCASABIT
WHERE CARI_ISIM LIKE '%'+CHAR(10) + CHAR(13)+'%'
but it doesn't return the records I need.
If I use double space character I can see the test record I put and some other records has double space character. So I can't be sure if other records have the same situation or not.
How can I handle this situation? Any help will be appreciated.
I believe you are getting the order of CHAR(10) and CHAR(13) backwards. Here is what each of these characters is:
CHAR(13) - carriage return, or \r
CHAR(10) - line feed, or \n
In Windows, \r\n is a line ending, while in Unix \n by itself is interpreted as a line ending. So you should be searching for CHAR(13) followed immediately by CHAR(10), and not the other way around. Try the following query:
SELECT *
FROM TBLCASABIT
WHERE CARI_ISIM LIKE '%' + CHAR(13) + CHAR(10) + '%'
References:
MSDN Social
DOS vs. Unix Line Endings

Using SQL Server to replace line breaks in columns with spaces

I have a large table of data where some of my columns contain line breaks. I would like to remove them and replace them with some spaces instead.
Can anybody tell me how to do this in SQL Server?
Thanks in advance
SELECT REPLACE(REPLACE(#str, CHAR(13), ''), CHAR(10), '')
This should work, depending on how the line breaks are encoded:
update t
set col = replace(col, '
', ' ')
where col like '%
%';
That is, in SQL Server, a string can contain a new line character.
#Gordon's answer should work, but in case you're not sure how your line breaks are encoded, you can use the ascii function to return the character value. For example:
declare #entry varchar(50) =
'Before break
after break'
declare #max int = len(#entry)
; with CTE as (
select 1 as id
, substring(#entry, 1, 1) as chrctr
, ascii(substring(#entry, 1, 1)) as code
union all
select id + 1
, substring(#entry, ID + 1, 1)
, ascii(substring(#entry, ID + 1, 1))
from CTE
where ID <= #max)
select chrctr, code from cte
print replace(replace(#entry, char(13) , ' '), char(10) , ' ')
Depending where your text is coming from, there are different encodings for a line break. In my test string I put the most common.
First I replace all CHAR(10) (Line feed) with CHAR(13) (Carriage return), then all doubled CRs to one CR and finally all CRs to the wanted replace (you want a blank, I put a dot for better visability:
Attention: Switch the output to "text", otherwise you wont see any linebreaks...
DECLARE #text VARCHAR(100)='test single 10' + CHAR(10) + 'test 13 and 10' + CHAR(13) + CHAR(10) + 'test single 13' + CHAR(13) + 'end of test';
SELECT #text
DECLARE #ReplChar CHAR='.';
SELECT REPLACE(REPLACE(REPLACE(#text,CHAR(10),CHAR(13)),CHAR(13)+CHAR(13),CHAR(13)),CHAR(13),#ReplChar);
I have the same issue, means I have a column having values with line breaks in it. I use the query
update `your_table_name` set your_column_name = REPLACE(your_column_name,'\n','')
And this resolves my issue :)
Basically '\n' is the character for Enter key or line break and in this query, I have replaced it with no space (which I want)
Keep Learning :)
zain

Remove a substring in a varchar field from multiple rows of a table

I would like to consult about the best way to remove a certain substring from a varchar field of every row in a table.
Let's assume I have a single column table, the column names is "user_list" and it is a varchar field that contain user names seperated by ";".
for example:
row1: james;david;moses
row2: mary;moses;terry
row3: ronaldo;messi;zlatan
the lists are not sorted in anyway.
I want to crate a SP that gets a username and removes it from every row it appears,
for instance if the db is the example above and i got as an input 'moses'
I would like it to look like
row1: james;david;
row2: mary;terry
row3: ronaldo;messi;zlatan
I want it to be a single update command and not a cursor, and i'm thinking with myself (and now with you) what is the best way to do it.
Thanks!
You have a very poor data structure. SQL has this great structure for storing lists of things. It is called a "table". In particular, you want a junction table instead of storing values as lists.
That said, you cannot always control how data is structured. The following should help:
update table t
set usernames = replace(replace(';' + usernames + ';', ';' + #UserName + ';', ''), ';;', ';')
where ';' + usernames + ';' like '%;' + #UserName + ';%';
This will put a semicolon at the beginning and the end of the list. If that is a problem, you can remove them using left() or stuff().
EDIT:
To remove the ; at the beginning, use stuff():
update table t
set usernames = stuff(replace(replace(';' + usernames + ';', ';' + #UserName + ';', ''), ';;', ';'), 1, 1, '')
where ';' + usernames + ';' like '%;' + #UserName + ';%';
Okay so I took what Gordon suggested and to resolve the problem i encountered (can be seen in the comments) I did the following (How didn't I think about it in the first place? :( )
update matan_test
SET usernames= replace(replace(mail_list,#UserName+';', ''), #UserName, '')
where usernames like '%'+#UserName+'%';