Replacing `:` with `-` while doing an `INSERT` statement - sql

I am trying to move some data into a program but the name field does not accept the : character. I would like to change the : to a - while doing the INSERT statement. The data I am moving is something like this "Revenue:A". I would like it to be "Revenue-A" when I move it.
I have tried the REPLACE statement in a nested SELECT statement with no luck. I have researched using a char index statement but do not understand how to make it change the code.
SELECT Account
, 'Accounts Receivable'
, (SELECT REPLACE([DESC], '%:%', '-'))
, (Select REPLACE(Account + ' - ' + [DESC], '%:%', '-'))
, ………
FROM ………
WHERE ………
The results that I get still include the :. When I try the code without the wildcard character it just returns - as the name, which will not work.

You don't need the select statements if the columns [DESC] and Account are columns from table(s) mentioned in your query:
,REPLACE([DESC], ':', '-')
,0,0
,REPLACE(Account + ' - ' + [DESC],':','-')
I removed % from the argument ':' (if you used it as a wildcard it does not work and it is not needed).

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.

Convert the Numeric data type to varchar without trailing Zeros in sybase

How to Convert the SQL data type Numerci(15,2) to string(varchar data type) without adding the trailing zeros in sybase.
Example- in column abc below values are present-
0.025
0.02
NULL
0.025589
5.289
on running the query-
select STR(column,10,4) from table --- produces the results 0.025,0.0200
select CAST(column as CHAR(5)) from table -- produces the results as 0.0250 etc
I can not do it in presentation layer
Can someone please help with query.
Unfortunately Sybase ASE does not have any native support for regex's, nor any out-of-the-box functions for stripping trailing zeros.
An obvious (?) first attempt might consist of a looping construct to strip off the trailing zeros, though it'd probably be easier to reverse() the initial string, strip off leading zeros, then reverse() to get back to the original value. Unfortunately this is not exactly efficient and would need to be encapsulated in a user-defined function (which introduces an additional performance hit each time it's invoked) in order to use it in a query.
The next idea would be to convert the zeros into something that can be (relatively) easily stripped off the end of the string, and it just so happens that ASE does provide the rtrim() function for stripping trailing spaces. This idea would look something like:
convert all zeros to spaces [str_replace('string','0',' ')]
strip off trailing spaces [rtrim('string')]
convert any remaining spaces back to zeros [str_replace('string',' ','0')]
** This obviously assumes the original string does not contain any spaces.
Here's an example:
declare #mystring varchar(100)
select #mystring = '0.025000'
-- here's a breakdown of each step in the process ...
select ':'+ #mystring + ':' union all
select ':'+ str_replace(#mystring,'0',' ') + ':' union all
select ':'+ rtrim(str_replace(#mystring,'0',' ')) + ':' union all
select ':'+ str_replace(rtrim(str_replace(#mystring,'0',' ')),' ','0') + ':'
-- and the final solution sans the visual end markers (:)
select str_replace(rtrim(str_replace(#mystring,'0',' ')),' ','0')
go
----------
:0.025000:
: . 25 :
: . 25:
:0.025:
--------
0.025
If you need to use this code snippet quite often then you may want to consider wrapping it in a user-defined function, though keep in mind there will be a slight performance hit each time the function is called.
Following approaches can be used -
1) It uses the Replace function
select COLUMN,str_replace(rtrim(str_replace(
str_replace(rtrim(str_replace(cast(COLUMN as varchar(15)), '0', ' ')), ' ', '0')
, '.', ' ')), ' ', '.')
from TABLE
Output -
0.0252
0.0252
2) Using Regex-
select COLUMN ,str(COLUMN ,10,3),
reverse(substring( reverse(str(COLUMN ,10,3)), patindex('%[^0]%',reverse(str(COLUMN ,10,3))), 10))
from TABLE
Output -
0.0252
0.0252.

splitting a column into individual words then filter results

I have a column where I would like to break it into individual words for an "auto suggest" on text box. I was able to accomplish this thanks to this article:
http://discourse.bigdinosaur.org/t/sql-and-database-splitting-a-column-into-individual-words/709/45
However, the results have characters that I don't want like "/' , etc.
I have a database function that I use when I want to filter out characters, but I cannot figure out how to merge the 2 and get it to work.
Here's the splitting code:
;WITH for_tally (spc_loc) AS
(SELECT 1 AS spc_loc
UNION ALL
SELECT spc_loc + 1 from for_tally WHERE spc_loc < 65
)
SELECT spc_loc into #tally from for_tally OPTION(MAXRECURSION 65)
select substring(name, spc_loc, charindex(' ', name + ' ', spc_loc) - spc_loc) as word
into #temptable
from #tally, products
where spc_loc <= convert(int, len(name))
and substring(' ' + name, spc_loc, 1) = ' '
Then, here's how I view the table:
select distinct word from #temptable order by word
Then here's how I call the database function in other queries:
SELECT * INTO #Keywords FROM dbo.SplitStringPattern(#Keywords, '[abcdefghijklmnopqrstuvwxyz0123456789-]')
Where #Keywords is the string to filter.
I've tried all I can think of, to filter the first query by the dbo.SplitStringPattern function
ie:
select substring(dbo.SplitStringPattern(name, '[abcdefghijklmnopqrstuvwxyz0123456789-]'), spc_loc, charindex(' ', name + ' ', spc_loc) - spc_loc) as word
into #temptable
from #tally, products
where spc_loc <= convert(int, len(name))
and substring(' ' + name, spc_loc, 1) = ' '
But I get "Cannot find either column "dbo" or the user-defined function or aggregate "dbo.SplitStringPattern", or the name is ambiguous."
I need this to be optimized as this query needs to return results very quick.
Or, if there's a better way of doing this, I'm open to suggestions.
Create a T-SQL Function to filter out the unwanted characters before your "database function" is called. The following web page links should help.
MSDN Create Function (Transact-SQL)
How to remove special characters from a string in MS SQL Server (T-SQL)

Running SQL query to remove all trailing and beginning double quotes only affects first record in result set

I'm having a problem when running the below query - it seems to ONLY affect the very first record. The query removes all trailing and beginning double quotes. The first query is the one that does this; the second query is just to demonstrate that there are multiple records that have beginning double quotes that I need removed.
QUESTION: As you can see the first record resulting from the top query is fine - it has its double quotes removed from the beginning. But all subsequent queries appear to be untouched. Why?
If quotes are always assumed to exist at both the beginning and the end, adjust your CASE statement to look for instances where both cases exist:
CASE
WHEN ([Message] LIKE '"%' AND [Message] LIKE '%"') THEN LEFT(RIGHT([Message], LEN([Message])-1),LEN([Message]-2)
ELSE [Message]
EDIT
If assumption is not valid, combine above syntax with your existing CASE logic:
CASE
WHEN ([Message] LIKE '"%' AND [Message] LIKE '%"') THEN LEFT(RIGHT([Message],LEN([Message])-1),LEN([Message]-2)
WHEN ([Message] LIKE '"%') THEN RIGHT([Message],LEN([Message]-1)
WHEN ([Message] LIKE '%"') THEN LEFT([Message],LEN([Message]-1)
ELSE [Message]
Because your CASE statement is only evaluating the first condition met, it will only ever remove one of the statements.
Try something like the following:
SELECT REPLACE(SUBSTRING(Message, 1, 1), '"', '') + SUBSTRING(Message, 2, LEN(Message) - 2) + REPLACE(SUBSTRING(Message, LEN(Message), 1), '"', '')
EDIT: As Martin Smith pointed out, my original code wouldn't work if a string was under two characters, so ...
CREATE TABLE #Message (Message VARCHAR(20))
INSERT INTO #Message (Message)
SELECT '"SomeText"'
UNION
SELECT '"SomeText'
UNION
SELECT 'SomeText"'
UNION
SELECT 'S'
SELECT
CASE
WHEN LEN(Message) >=2
THEN REPLACE(SUBSTRING(Message, 1, 1), '"', '') + SUBSTRING(Message, 2, LEN(Message) - 2) + REPLACE(SUBSTRING(Message, LEN(Message), 1), '"', '')
ELSE Message
END AS Message
FROM #Message
DROP TABLE #Message
Try this:
SELECT REPLACE([Message], '"', '') AS [Message] FROM SomeTable

How can I remove leading and trailing quotes in SQL Server?

I have a table in a SQL Server database with an NTEXT column. This column may contain data that is enclosed with double quotes. When I query for this column, I want to remove these leading and trailing quotes.
For example:
"this is a test message"
should become
this is a test message
I know of the LTRIM and RTRIM functions but these workl only for spaces. Any suggestions on which functions I can use to achieve this.
I have just tested this code in MS SQL 2008 and validated it.
Remove left-most quote:
UPDATE MyTable
SET FieldName = SUBSTRING(FieldName, 2, LEN(FieldName))
WHERE LEFT(FieldName, 1) = '"'
Remove right-most quote: (Revised to avoid error from implicit type conversion to int)
UPDATE MyTable
SET FieldName = SUBSTRING(FieldName, 1, LEN(FieldName)-1)
WHERE RIGHT(FieldName, 1) = '"'
I thought this is a simpler script if you want to remove all quotes
UPDATE Table_Name
SET col_name = REPLACE(col_name, '"', '')
You can simply use the "Replace" function in SQL Server.
like this ::
select REPLACE('this is a test message','"','')
note: second parameter here is "double quotes" inside two single quotes and third parameter is simply a combination of two single quotes. The idea here is to replace the double quotes with a blank.
Very simple and easy to execute !
My solution is to use the difference in the the column values length compared the same column length but with the double quotes replaced with spaces and trimmed in order to calculate the start and length values as parameters in a SUBSTRING function.
The advantage of doing it this way is that you can remove any leading or trailing character even if it occurs multiple times whilst leaving any characters that are contained within the text.
Here is my answer with some test data:
SELECT
x AS before
,SUBSTRING(x
,LEN(x) - (LEN(LTRIM(REPLACE(x, '"', ' ')) + '|') - 1) + 1 --start_pos
,LEN(LTRIM(REPLACE(x, '"', ' '))) --length
) AS after
FROM
(
SELECT 'test' AS x UNION ALL
SELECT '"' AS x UNION ALL
SELECT '"test' AS x UNION ALL
SELECT 'test"' AS x UNION ALL
SELECT '"test"' AS x UNION ALL
SELECT '""test' AS x UNION ALL
SELECT 'test""' AS x UNION ALL
SELECT '""test""' AS x UNION ALL
SELECT '"te"st"' AS x UNION ALL
SELECT 'te"st' AS x
) a
Which produces the following results:
before after
-----------------
test test
"
"test test
test" test
"test" test
""test test
test"" test
""test"" test
"te"st" te"st
te"st te"st
One thing to note that when getting the length I only need to use LTRIM and not LTRIM and RTRIM combined, this is because the LEN function does not count trailing spaces.
I know this is an older question post, but my daughter came to me with the question, and referenced this page as having possible answers. Given that she's hunting an answer for this, it's a safe assumption others might still be as well.
All are great approaches, and as with everything there's about as many way to skin a cat as there are cats to skin.
If you're looking for a left trim and a right trim of a character or string, and your trailing character/string is uniform in length, here's my suggestion:
SELECT SUBSTRING(ColName,VAR, LEN(ColName)-VAR)
Or in this question...
SELECT SUBSTRING('"this is a test message"',2, LEN('"this is a test message"')-2)
With this, you simply adjust the SUBSTRING starting point (2), and LEN position (-2) to whatever value you need to remove from your string.
It's non-iterative and doesn't require explicit case testing and above all it's inline all of which make for a cleaner execution plan.
The following script removes quotation marks only from around the column value if table is called [Messages] and the column is called [Description].
-- If the content is in the form of "anything" (LIKE '"%"')
-- Then take the whole text without the first and last characters
-- (from the 2nd character and the LEN([Description]) - 2th character)
UPDATE [Messages]
SET [Description] = SUBSTRING([Description], 2, LEN([Description]) - 2)
WHERE [Description] LIKE '"%"'
You can use following query which worked for me-
For updating-
UPDATE table SET colName= REPLACE(LTRIM(RTRIM(REPLACE(colName, '"', ''))), '', '"') WHERE...
For selecting-
SELECT REPLACE(LTRIM(RTRIM(REPLACE(colName, '"', ''))), '', '"') FROM TableName
you could replace the quotes with an empty string...
SELECT AllRemoved = REPLACE(CAST(MyColumn AS varchar(max)), '"', ''),
LeadingAndTrailingRemoved = CASE
WHEN MyTest like '"%"' THEN SUBSTRING(Mytest, 2, LEN(CAST(MyTest AS nvarchar(max)))-2)
ELSE MyTest
END
FROM MyTable
Some UDFs for re-usability.
Left Trimming by character (any number)
CREATE FUNCTION [dbo].[LTRIMCHAR] (#Input NVARCHAR(max), #TrimChar CHAR(1) = ',')
RETURNS NVARCHAR(max)
AS
BEGIN
RETURN REPLACE(REPLACE(LTRIM(REPLACE(REPLACE(#Input,' ','¦'), #TrimChar, ' ')), ' ', #TrimChar),'¦',' ')
END
Right Trimming by character (any number)
CREATE FUNCTION [dbo].[RTRIMCHAR] (#Input NVARCHAR(max), #TrimChar CHAR(1) = ',')
RETURNS NVARCHAR(max)
AS
BEGIN
RETURN REPLACE(REPLACE(RTRIM(REPLACE(REPLACE(#Input,' ','¦'), #TrimChar, ' ')), ' ', #TrimChar),'¦',' ')
END
Note the dummy character '¦' (Alt+0166) cannot be present in the data (you may wish to test your input string, first, if unsure or use a different character).
To remove both quotes you could do this
SUBSTRING(fieldName, 2, lEN(fieldName) - 2)
you can either assign or project the resulting value
You can use TRIM('"' FROM '"this "is" a test"') which returns: this "is" a test
CREATE FUNCTION dbo.TRIM(#String VARCHAR(MAX), #Char varchar(5))
RETURNS VARCHAR(MAX)
BEGIN
RETURN SUBSTRING(#String,PATINDEX('%[^' + #Char + ' ]%',#String)
,(DATALENGTH(#String)+2 - (PATINDEX('%[^' + #Char + ' ]%'
,REVERSE(#String)) + PATINDEX('%[^' + #Char + ' ]%',#String)
)))
END
GO
Select dbo.TRIM('"this is a test message"','"')
Reference : http://raresql.com/2013/05/20/sql-server-trim-how-to-remove-leading-and-trailing-charactersspaces-from-string/
I use this:
UPDATE DataImport
SET PRIO =
CASE WHEN LEN(PRIO) < 2
THEN
(CASE PRIO WHEN '""' THEN '' ELSE PRIO END)
ELSE REPLACE(PRIO, '"' + SUBSTRING(PRIO, 2, LEN(PRIO) - 2) + '"',
SUBSTRING(PRIO, 2, LEN(PRIO) - 2))
END
Try this:
SELECT left(right(cast(SampleText as nVarchar),LEN(cast(sampleText as nVarchar))-1),LEN(cast(sampleText as nVarchar))-2)
FROM TableName