MSSQL remove enter space only with empty row in one cell - sql-server

I have a table in Excel. This table I load to MSSQL through SSIS. In the table is column TEXT that contains multiple sentences in one cell separated by enter spaces (alt + enter). My table looks like this:
NAME
ID
TEXT
JOHN SMITH
125
TEXT TEXT TEXT
But sometimes I have in column TEXT more enter spaces without text, like this:
NAME
ID
TEXT
JOHN SMITH
125
TEXT TEXT TEXT
I need to remove excess line breaks but keep enter space after each TEXT.

In basic case you can use REPLACE function for replace duplicates
UPDATE T SET T.T = REPLACE(T.T, CHAR(10) + CHAR(10), CHAR(10))
WHERE T.T LIKE('%' + CHAR(10) + CHAR(10) + '%')
But this query replace ONLY duplicates, so in case 3 or more duplicates you need repeat the query. For automate this you can use PROCEDURE like next:
CREATE PROCEDURE cleanDupes
AS
BEGIN
DECLARE #count INT
SET #count = 1
WHILE #count > 0
BEGIN
UPDATE T SET T.T = REPLACE(T.T, CHAR(10) + CHAR(10), CHAR(10))
WHERE T.T LIKE('%' + CHAR(10) + CHAR(10) + '%')
SET #count = (SELECT COUNT(*) FROM T WHERE T.T LIKE('%' + CHAR(10) + CHAR(10) + '%'))
END
SELECT * FROM T
END
GO
Test this solution on https://sqlize.online/sql/mssql2019/3ce3f73e8d27862fd7d268523a4a4a14/

Related

New line in ssrs expression

I have an expression that suppose to be in one line. But the the number is jumping into another line in the textbox. What can I do to make it in one line.
The output is giving
2018-06-26HP-HPP
4
Code :
=Trim(Format(CDate(Fields!Startdate.Value), "yyyy-MM-dd")) & Trim(Fields!Register.Value) & Trim(DatePart(DateInterval.Hour, Fields!GSTIME.Value)).ToString()
Expected answer should be :
2018-06-26HP-HPP4
Thanks
Michael
If this is your expected result
2018-06-26HP-HPP4
from
=Trim(Format(CDate(Fields!Startdate.Value), "yyyy-MM-dd")) & Trim(Fields!Register.Value) & Trim(DatePart(DateInterval.Hour, Fields!GSTIME.Value)).ToString()
but you're getting this
2018-06-26HP-HPP
4
And the text box is large enough to show this on one line then I suspect you have a new line character in the field Fields!Register.Value
because
the first part of the expected result (2018-06-26) comes from
Trim(Format(CDate(Fields!Startdate.Value), "yyyy-MM-dd"))
The second part (HP-HPP) comes from this
Trim(Fields!Register.Value)
The final part (4) comes from this
Trim(DatePart(DateInterval.Hour, Fields!GSTIME.Value)).ToString()
The new line you're seeing in the text box is between the 2nd and 3rd parts which I suspect may be in the contents of Trim(Fields!Register.Value)
If this field is in a db table then when you select the column search and replace for hidden carriage returns, line feeds and tabs.
Here's one way
DECLARE #tmp TABLE (tmp NVARCHAR(50))
INSERT INTO #tmp (tmp)
SELECT 'Help' + CHAR(10) + 'me' + CHAR(9) + 'please' + CHAR(13)
DECLARE #val NVARCHAR(50) = (SELECT tmp FROM #tmp )
PRINT #val
output
Help
me please
remove the hidden characters
SET #val = (SELECT REPLACE(REPLACE(REPLACE(ISNULL(tmp,' '), CHAR(10), ' '), CHAR(13), ' '), CHAR(9), ' ') FROM #tmp )
PRINT #val
output
Help me please

SQL Server Full Text Search to match contact name to prevent duplicates

Using SQL Server Azure or 2017 with Full Text Search, I need to return possible matches on names.
Here's the simple scenario: an administrator is entering contact information for a new employee, first name, last name, address, etc. I want to be able to search the Employee table for a possible match on the name(s) to see if this employee has already been entered in the database.
This might happen as an autosuggest type of feature, or simply display some similar results, like here in Stackoverflow, while the admin is entering the data.
I need to prevent duplicates!
If the admin enters "Bob", "Johnson", I want to be able to match on:
Bob Johnson
Rob Johnson
Robert Johnson
This will give the administrator the option of seeing if this person has already been entered into the database and choose one of those choices.
Is it possible to do this type of match on words like "Bob" and include "Robert" in the results? If so, what is necessary to accomplish this?
Try this.
You need to change the #per parameter value to your requirement. It indicates how many letters out of the length of the first name should match for the result to return. I just set it to 50% for testing purposes.
The dynamic SQL piece inside the loop adds all the CHARINDEX result per letter of the first name in question, to all existing first names.
Caveats:
Repeating letters will of course be misleading, like Bob will count 3 matches in Rob because there's 2 Bs in Bob.
I didn't consider 2 first names, like Bob Robert Johnson, etc so this will fail. You can improve on that however, but you get the idea.
The final SQL query gets the LetterMatch that is greater than or equal to the set value in #per.
DECLARE #name varchar(MAX) = 'Bobby Johnson' --sample name
DECLARE #first varchar(50) = SUBSTRING(#name, 0, CHARINDEX(' ', #name)) --get the first part of the name before space
DECLARE #last varchar(50) = SUBSTRING(#name, CHARINDEX(' ', #name) + 1, LEN(#name) - LEN(#first) - 1) --get the last part of the name after space
DECLARE #walker int = 1 --for looping
DECLARE #per float = LEN(#first) * 0.50 --declare percentage of how many letters out of the length of the first name should match. I just used 50% for testing
DECLARE #char char --for looping
DECLARE #sql varchar(MAX) --for dynamic SQL use
DECLARE #matcher varchar(MAX) = '' --for dynamic SQL use
WHILE #walker <> LEN(#first) + 1 BEGIN --loop through all the letters of the first name saved in #first variable
SET #char = SUBSTRING(#first, #walker, 1) --save the current letter in the iteration
SET #matcher = #matcher + IIF(#matcher = '', '', ' + ') + 'IIF(CHARINDEX(''' + #char + ''', FirstName) > 0, 1, 0)' --build the additional column to be added to the dynamic SQL
SET #walker = #walker + 1 --move the loop
END
SET #sql = 'SELECT * FROM (SELECT FirstName, LastName, ' + #matcher + ' AS LetterMatch
FROM TestName
WHERE LastName LIKE ' + '''%' + #last + '%''' + ') AS src
WHERE CAST(LetterMatch AS int) >= ROUND(' + CAST(#per AS varchar(50)) + ', 0)'
SELECT #sql
EXEC(#sql)
SELECT * FROM tbl_Names
WHERE Name LIKE '% user defined text %';
using a text in between % % will search those text on any position in the data.

Generate column name dynamically in sql server

Please look at the below query..
select name as [Employee Name] from table name.
I want to generate [Employee Name] dynamically based on other column value.
Here is the sample table
s_dt dt01 dt02 dt03
2015-10-26
I want dt01 value to display as column name 26 and dt02 column value will be 26+1=27
I'm not sure if I understood you correctly. If I'am going into the wrong direction, please add comments to your question to make it more precise.
If you really want to create columns per sql you could try a variation of this script:
DECLARE #name NVARCHAR(MAX) = 'somename'
DECLARE #sql NVARCHAR(MAX) = 'ALTER TABLE aps.tbl_Fabrikkalender ADD '+#name+' nvarchar(10) NULL'
EXEC sys.sp_executesql #sql;
To retrieve the column name from another query insert the following between the above declares and fill the placeholders as needed:
SELECT #name = <some colum> FROM <some table> WHERE <some condition>
You would need to dynamically build the SQL as a string then execute it. Something like this...
DECLARE #s_dt INT
DECLARE #query NVARCHAR(MAX)
SET #s_dt = (SELECT DATEPART(dd, s_dt) FROM TableName WHERE 1 = 1)
SET #query = 'SELECT s_dt'
+ ', NULL as dt' + RIGHT('0' + CAST(#s_dt as VARCHAR), 2)
+ ', NULL as dt' + RIGHT('0' + CAST((#s_dt + 1) as VARCHAR), 2)
+ ', NULL as dt' + RIGHT('0' + CAST((#s_dt + 2) as VARCHAR), 2)
+ ', NULL as dt' + RIGHT('0' + CAST((#s_dt + 3) as VARCHAR), 2)
+ ' FROM TableName WHERE 1 = 1)
EXECUTE(#query)
You will need to replace WHERE 1 = 1 in two places above to select your data, also change TableName to the name of your table and it currently puts NULL as the dynamic column data, you probably want something else there.
To explain what it is doing:
SET #s_dt is selecting the date value from your table and returning only the day part as an INT.
SET #query is dynamically building your SELECT statement based on the day part (#s_dt).
Each line is taking #s_dt, adding 0, 1, 2, 3 etc, casting as VARCHAR, adding '0' to the left (so that it is at least 2 chars in length) then taking the right two chars (the '0' and RIGHT operation just ensure anything under 10 have a leading '0').
It is possible to do this using dynamic SQL, however I would also consider looking at the pivot operators to see if they can achieve what you are after a lot more efficiently.
https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx

How can i Remove \n (Char(10)) from specific string from starting & Ending of the string in ms sql

I have one column for comment and I need to show this for one report.
Here what happen some time, users uses multiple enters in comment box. I can not access code part I need to manage this thing in SQL only.
So I have removed unwanted
1 /r/n
2 /n/n
from using
REPLACE(REPLACE(Desc, CHAR(13)+CHAR(10), CHAR(10)),CHAR(10)+CHAR(10), CHAR(10)) as Desc,
Now I want to remove any \r or \n from starting or ending of the string if any
By the way you meant in your question:(Remove char(10) or char(13) from specific string)
Note: You should see the output result by switching your resultset output to Results to Text(Ctrl+T).
Results to Text
Results to Grid
Use TRIM check here
Example : UPDATE tablename SET descriptions = TRIM(TRAILING "<br>" FROM descriptions)
if you want to replace newline then use something like below
SELECT REPLACE(REPLACE(#str, CHAR(13), ''), CHAR(10), '')
or
DECLARE #testString varchar(255)
set #testString = 'MY STRING '
/*Select the string and try to copy and paste into notepad and tab is still there*/
SELECT testString = #testString
/*Ok, it seems easy, let's try to trim this. Huh, it doesn't work, the same result here.*/
SELECT testStringTrim = RTRIM(#testString)
/*Let's try to get the size*/
SELECT LenOfTestString = LEN(#testString)
/*This supposed to give us string together with blank space, but not for tab though*/
SELECT DataLengthOfString= DATALENGTH(#testString)
SELECT ASCIIOfTab = ASCII(' ')
SELECT CHAR(9)
/*I always use this like a final solution*/
SET #testString = REPLACE(REPLACE(REPLACE(#testString, CHAR(9), ''), CHAR(10), ''), CHAR(13), '') SELECT #testString
/*
CHAR(9) - Tab
CHAR(10) - New Line
CHAR(13) - Carriage Return
*/
Reference
select dbo.trim('abc','c') -- ab
select dbo.trim('abc','a') -- bc
select dbo.trim(' b ',' ') -- b
Create a user-define-function: trim()
trim from both sides
trim any letter: space, \r, \n, etc
Create FUNCTION Trim
(
#Original varchar(max), #letter char(1)
)
RETURNS varchar(max)
AS
BEGIN
DECLARE #rtrim varchar(max)
SELECT #rtrim = iif(right(#original, 1) = #letter, left(#original,datalength(#original)-1), #original)
return iif( left(#rtrim,1) = #letter, right(#rtrim,datalength(#rtrim)-1),#rtrim)
END

Search Entire Database To find extended ascii codes in sql

We have issues with extended ascii codes getting in our database (128-155)
Is there anyway to search the entire database and display the results of any of these characters that may be in there and where they are located within the tables and columns.
Hope that makes sense.
I have the script to search entire DB, but having trouble with opening line.
DECLARE #SearchStr nvarchar(100)
SET #SearchStr != between char(32) and char(127)
I have this originally that works, but I need to extend the range I'm looking for.
SET #SearchStr = '|' + char(9) + '|' + char(10) + '|' + char(13)
Thanks
It's very unclear what your data looks like, but this might help you to get started:
declare #TestData table (String nvarchar(100))
insert into #TestData select N'abc'
insert into #TestData select N'def'
insert into #TestData select char(128)
insert into #TestData select char(155)
declare #SearchPattern nvarchar(max) = N'%['
declare #i int = 128
while #i <= 155
begin
set #SearchPattern += char(#i)
set #i += 1
end
set #SearchPattern += N']%'
select #SearchPattern
select String
from #TestData
where String like #SearchPattern
Of course you'll need to add some code to loop over every table and column that you want to query (see this question), and it's possible that this code will behave differently on different collations.
... where dodgyColumn is your column with questionable data ....
WHERE(patindex('%[' + char(127) + '-' + char(255) + ']%', dodgyColumn COLLATE Latin1_General_BIN2) > 0)
This works for us, to identify extended ASCII characters in our otherwise normal ASCII data (characters, numbers, punctuation, dollar and percent signs, etc.)

Resources