I have a situation where i need to replace the entire text and the square bracket with a single charecter inside stored procedure.
( Iam using Sql Server 2012).
Eg:->
Let us consider that i have a text san[123456dd]text
i just wanted to replace all the text inside the square bracket and square bracket itself with another charecter say 'X'
Here, My end result should be sanXtext.
Could anyone help me regarding this?
DECLARE #String VARCHAR(1000) = 'san[123456dd]text'
SELECT LEFT(#String, CHARINDEX('[', #String)-1) +'X' +
RIGHT(#String, CHARINDEX(']', REVERSE(#String))-1)
Result: sanXtext
SELECT REPLACE(col,SUBSTRING(col, (CHARINDEX('[',col)), CHARINDEX(']',col) -
(CHARINDEX('[', col)) + Len(']')),'x')
FROM tableName
Fiddle
Related
Is it posible that an ms sql query to return only a portion of what is stored in a field?
For example, I got this data stored in the field:
row NGV1="" NGV10="*" NGV6=" " NGV5=" " NGV4=" " NGV3=" " NGV2=" " _tipprodus="NGV" lotuloptim="20" /
I only need to display the value that is between the quotation marks from this part lotuloptim="20". The result should be 20.
Thank you in advance.
Best regards
Yes, you can use SUBSTRING, but using substring you need to know the start index
SELECT SUBSTRING(column_name,start,length) AS some_name FROM table_name;
and then you can use CHARINDEX to find the index for example to the lotuloptim word
DECLARE #document varchar(64);
SELECT #document = 'Reflectors are vital safety' +
' components of your bicycle.';
SELECT CHARINDEX('bicycle', #document);
GO
I have a table storing pathes to files on sql server. I need to replace the path before the last backslash:
C:\Users\APP\AppData\Local\Temp\test\abc deg.pdf
to for example:
\app\pp\abc deg.pdf
EDIT: The table containts many pathes - I need to run through the whole table and change all pathes.
You can use:
CHARINDEX('\', REVERSE(#str))
to get the index of the first backslash starting from the end.
Using RIGHT with this index you can extract the string after the last backslash and concatenate it to the new path:
DECLARE #str VARCHAR(50) = 'C:\Users\APP\AppData\Local\Temp\test\abc deg.pdf'
SELECT '\app\pp' + RIGHT(#str, CHARINDEX('\', REVERSE(#str)))
Reverse the input string (using REVERSE) and find the index of the first backslash (using CHARINDEX).
Take the left part up to that index (using LEFT) and concatenate with the reverse of your replacement string (using + operator).
Then reverse that to get your final result.
Try this:
declare #a varchar(max)='C:\Users\APP\AppData\Local\Temp\test\abc deg.pdf'
select REPLACE(#a,SUBSTRING(#a,1,(LEN(#a)-charindex('\',reverse(#a),1))),'\app\pp')
Update: For updatingall the table column values.
select REPLACE([column-name],SUBSTRING([column-name],1,(LEN([column-name])-charindex('\',reverse([column-name]),1))),'\app\pp')
FROM [Your-table]
This is how it can be done.
UPDATE TABLE
SET PATH = REPLACE(PATH, 'C:\Users\APP\AppData\Local\Temp\test', '\app\pp')
WHERE ...
This is going to replace 'C:\Users\APP\AppData\Local\Temp\test' with '\app\pp'. Or you can modify the path as required.
Please test before executing this UPDATE statement. I havent specified filters here
My stored procedure receives a parameter which is a comma-separated string:
DECLARE #review_status varchar(200)
SET #review_status='CANCELLED,INSPECTED,REJECTED,UNASSIGNED'
I use this variable with LIKE Operator, when value without comma then perfect but it comes with comma then unable to handle.
Now i use this statement
SELECT * FROM tblReview WHERE
review_status LIKE '%' + #review_status + '%'
I need to make from it this statement
SELECT * FROM tblReview WHERE
review_status LIKE '%CANCELLED%' OR --Pass #review_status
review_status LIKE '%INSPECTED%' OR
review_status LIKE '%REJECTED%'.....
What is the best practice for doing this?
You could use a string splitter to do this. Read this article for one of the fastest splitter there is.
Then you need to use the IN operator to do the filtering:
SELECT *
FROM tblReview
WHERE review_status IN(
SELECT item FROM dbo.DelimitedSplit8K(#review_status,',')
)
Since you're using LIKE, you may want to do JOIN instead of IN:
SELECT *
FROM tblReview t
INNER JOIN dbo.DelimitedSplit8K(#review_status, ',') s
ON t.review_status LIKE '%' + s.Item + '%'
Try to first convert varchar with commas to a table as described here http://blogs.msdn.com/b/amitjet/archive/2009/12/11/sql-server-comma-separated-string-to-table.aspx. Then, use the following:
CREATE TABLE #allPattern (
pattern NVARCHAR(max)
);
INSERT INTO #allPattern VALUES ('%CANCELLED%'), ('%INSPECTED%'), ('%REJECTED%');
SELECT t.* FROM tblReview t JOIN #allPattern a ON (t.review_status LIKE a.pattern);
You can add the pre- and trailing comma to yous string, and then use CHARINDEX().
SET #review_status=',CANCELLED,INSPECTED,REJECTED,UNASSIGNED,'
SELECT * FROM tblReview WHERE
charindex(','+review_status+',', '#review_status') >0
Commas at the beginning and at the end of the string are used to make an exact string finding possible - for example, if you have two statuses - one called CAN and the second called CANCELLED, charindex without side commas will find them both.
It's the simplest way, but not the one with the best performance, so don't use it on long CSVs.
I need to fetch Table's TOP_PK, IDENT_CURRENT, IDENT_INCR, IDENT_SEED for which i am building dynamic query as below:
sGetSchemaCommand = String.Format("SELECT (SELECT TOP 1 [{0}] FROM [{1}]) AS TOP_PK, IDENT_CURRENT('[{1}]') AS CURRENT_IDENT, IDENT_INCR('[{1}]') AS IDENT_ICREMENT, IDENT_SEED('[{1}]') AS IDENT_SEED", pPrimaryKey, pTableName)
Here pPrimaryKey is name of Table's primary key column and pTableName is name of Table.
Now, i am facing problem when Table_Name contains " ' " character.(For Ex. KIN'1)
When i am using above logic and building query it would be as below:
SELECT (SELECT TOP 1 [ID] FROM [KIL'1]) AS TOP_PK, IDENT_CURRENT('[KIL'1]') AS CURRENT_IDENT, IDENT_INCR('[KIL'1]') AS IDENT_ICREMENT, IDENT_SEED('[KIL'1]') AS IDENT_SEED
Here, by executing above query i am getting error as below:
Incorrect syntax near '1'.
Unclosed quotation mark after the character string ') AS IDENT_SEED'.
So, can anyone please show me the best way to solve this problem?
Escape a single quote by doubling it: KIL'1 becomes KIL''1.
If a string already has adjacent single quotes, two becomes four, or four becomes eight... it can get a little hard to read, but it works :)
Using string methods from .NET, your statement could be:
sGetSchemaCommand = String.Format("SELECT (SELECT TOP 1 [{0}] FROM [{1}]) AS TOP_PK, IDENT_CURRENT('[{2}]') AS CURRENT_IDENT, IDENT_INCR('[{2}]') AS IDENT_ICREMENT, IDENT_SEED('[{2}]') AS IDENT_SEED", pPrimaryKey, pTableName, pTableName.Replace("'","''"))
EDIT:
Note that the string replace is now only on a new, third substitution string. (I've taken out the string replace for pPrimaryKey, and for the first occurrence of pTableName.) So now, single quotes are only doubled, when they will be within other single quotes.
You need to replace every single quote into two single quotes http://beyondrelational.com/modules/2/blogs/70/posts/10827/understanding-single-quotes.aspx
I have been seraching solution for this issue .Though this particular question has been discussed many times in this forum, i did not get any proper answer for my problem.
I will be getting data from 3rd party which can contain single quote.This data need to be inserted into data base and when it contains single quote it fails and throws following error:
Msg 105, Level 15, State 1, Line 7
Unclosed quotation mark after the character string '
---Following is c++ code to pass trandata as input along with other parameters and invoke fn_stripsingleQuote10 function from SQL server:
strSQLText = "declare #returnType as varchar(max)\n EXEC #returnType = CABINET..fn_stripsingleQuote10 ";
sqlTxtParams.Format("'%s', '%s', '%s', tranData, sing_quote, double_sing_quote);
strSQLText += sqlTxtParams;
----My sql function(fn_stripsingleQuote10) to replace single quote
USE [cabinet]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE function [dbo].[fn_stripsingleQuote10](
#strip varchar(Max),#patern varchar(5),#replace varchar(5)
)
returns varchar(Max) as begin
declare #CleanString varchar(Max)
SET #CleanString=(REPLACE(#strip,#patern, #replace))
return #CleanString
end
sample output:
ex:
declare #returnType as varchar(max) EXEC #returnType = CABINET..fn_stripsingleQuote10 'fsds'd','''',''''''
I feel the way i am invoking the function is not proper.Please provide a solution .
Strictly speaking you're looking for QUOTENAME, which does exactly what you're asking:
'quote_character' Is a one-character string to use as the delimiter.
Can be a single quotation mark ( ' ), a left or right bracket ( [ ] ),
or a double quotation mark ( " ).
However, it is very very likely that your code is exposed to SQL Injection right now and you should actually use a parameter. It is almost never required to concatenate input into the resulted executed SQL.