substring or rtrim - sql-server

i have a field called LastWebpage, in the Field it stores the webpage .asp pagename
I have to write a script where i just need to take the jl_AssessmentDirect.asp name instead of 4000_1_jl_AssessmentDirect.asp. How do i get rid of 4000_1_. Please help.
Thanks.

Here are a couple of ways to do this, I assume the data is not always the same, this is just to show you how the functions work
right or replace is my preferred method
DECLARE #v VARCHAR(100)
SELECT #v = '4000_1_jl_AssessmentDirect.asp'
SELECT REPLACE(#v,'4000_1_','')
or
DECLARE #v VARCHAR(100)
SELECT #v = '4000_1_jl_AssessmentDirect.asp'
DECLARE #r VARCHAR(100)
SELECT #r ='4000_1_'
--if you have spaces RTRIM and LTRIM everything
SELECT RIGHT(#v,LEN(#v) -LEN(#r))
If stuff changes, you can dump it in variables
DECLARE #v VARCHAR(100)
SELECT #v = '4000_1_jl_AssessmentDirect.asp'
DECLARE #r VARCHAR(100)
SELECT #r ='4000_1_'
SELECT REPLACE(#v,#r,'')
Ideally you want to update such columns to only have the URL and nothing else

"It depends"
If always "4000_1_", use REPLACE as per SQLMenace's answer.
If a fixed length of any string, use SUBSTRING. No need to work out LENGTH first
SUBSTRING(MyValue, 8, 8000)
If the right hand side is fixed length and the unwanted part is variable length, use RIGHT
If both sides are variable, you'll need something like
SUBSTRING(MyValue, PATINDEX('%[_]1[_]%', MyValue) + 3, 8000)
Edit:
If you always want "jl"...
SUBSTRING(MyValue, PATINDEX('%jl%', MyValue), 8000)

Besides all the suggestions here already you can use stuff.
declare #s varchar(100)
set #s = '4000_1_jl_AssessmentDirect.asp'
select stuff(#s, 1, 7, '')
Remove characters before jl
declare #s varchar(100)
set #s = '4000_1_jl_AssessmentDirect.asp'
select stuff(#s, 1, charindex('jl', #s)-1, '')

Related

RTrim is not working when sentence is Arabic

RTrim is not working when sentence is Arabic.
Below is the example
declare #name nvarchar(50);
set #name = N' لللييب بي  ';
select rtrim(ltrim(#name));
English one is working
declare #name nvarchar(50);
set #name = ' This is test message ';
select rtrim(ltrim(#name));
Please try the following.
Casting as VARBINARY data type allows to see what exact characters represent white spaces in the string. It could be SPACE character (0x2000), but could be something else. If it is something else, the LTRIM() and RTRIM() functions won't work.
SQL
DECLARE #name NVARCHAR(50) ;
SET #name = N' لللييب بي ' COLLATE Arabic_CI_AI_KS_WS;
SELECT #name AS [Before], DATALENGTH(#name) AS [Before_Len]
, TRY_CAST(#name AS VARBINARY(30)) AS [Before_Binary]
, RTRIM(LTRIM(#name)) AS [After], DATALENGTH(RTRIM(LTRIM(#name))) AS [After_Len];
-- check available Arabic collations
SELECT * FROM sys.fn_helpcollations()
WHERE name LIKE 'Arabic%';
Before
Before_Len
Before_Binary
After
After_Len
لللييب بي
24
0x20004406440644064A064A062806200028064A0620002000
لللييب بي
18

Remove a value from a comma separated string in sql stored procedure

I have a field that store the comma separated id's of publications. Such as 123456,2345678,123567,2345890 etc. When I pull the data from the database I put it into a json object and the web page loops the values and displays the data. Works great.
What I would like to do is to send the stored proc one of the numbers and the stored proc will remove it from the string and save it back to the table. Such as the end user worked on publication 123567 and now wants to make it completed, so I want to remove it from the string so they don't see it in the future. I have a split function in the database but I don't know how to wire it up to delete or rebuild the string without the publication ID.
I don't have any code to show because I am at a loss to start. I figure I need to pass the entire string and the ID. Split the string and loop each value to rebuild a new string but check if the ID is there and skip it.
Is this the best way to do this?
Thanks for your help
what I've ended up with as the base to work from is:
ALTER FUNCTION dbo.RemovePMID (
#S VARCHAR(MAX)
,#PMID VARCHAR(15)
)
RETURNS VARCHAR(MAX)
AS
BEGIN
DECLARE #T VARCHAR(50)
DECLARE #W VARCHAR(50)
SET #T = ''
WHILE len(#S) > 0
BEGIN
SET #W = left(#S, charindex(',', #S + ',') - 1)
IF charindex(#W, + #PMID) = 0
SET #T = #T + ',' + #W
SET #S = stuff(#S, 1, charindex(',', #S + ','), '')
END
RETURN substring(#T, 2, len(#T) - 2)
END
GO
No need for loops (please take a peek at Larnu's suggestion for your parse/split function)
That said, consider the following
Example
Declare #S varchar(max) = '123456,2345678,123567,2345890'
Declare #Zap varchar(50)='123456'
Select reverse(stuff(reverse(stuff(replace(','+#S+',',','+#Zap+',',','),1,1,'')),1,1,''))
Returns
2345678,123567,2345890

Single quotes in variable in T-SQL

I have a condition where user will pass comma separated values like
0071061386,0071061387
it will be passed to a variable which will feed the values into a dynamic query with two single quotes.
passed by user
declare #s nvarchar(max) = '0071061386,0071061387'
it should be like after converting the user values so that I can pass the values into dynamic query
declare #s nvarchar(max) = '''0071061386'',''0071061387'''
A simple replace with probably do the trick here, but I beleive this to be an XYProblem. Perhaps you better explain the problem leading you to go this path in the first place.
declare #s nvarchar(max) = '0071061386,0071061387'
SELECT '''''' + REPLACE(#s, ',', ''''',''''') + ''''''
Result:
''0071061386'',''0071061387''
Try this
DECLARE #S NVARCHAR(MAX) = '0071061386,0071061387'
SELECT REPLACE(''''''''+#S+'''''''',',',''''',''''')

Substring select string between two characters

The following code
declare #text VARCHAR(MAX)
set #text='[Dim Company].[Company].[23]'
SELECT SUBSTRING(#Text, CHARINDEX('[Dim Company].[Company].[', #Text)
, CHARINDEX(']',#text) - CHARINDEX('[Dim Company].[Company].[', #Text) + Len(']'))
Returns [Dim Company]. I was expecting it to return the integer between the last [] -- in this case 23. How can I get the desired field?
If you know it's always last, why not REVERSE the string, find the value between the first pair of brackets, then REVERSE that result?
Much easier than nesting CHARINDEX calls.
This will give you 23]
SELECT RIGHT(#text, CHARINDEX('[',REVERSE(#text))-1)
This will give you 23
SET #tmp = RIGHT(#text, CHARINDEX('[',REVERSE(#text))-1)
SET #tmp = LEFT(#tmp, LEN(tmp)-1)
fiddle : http://sqlfiddle.com/#!3/d41d8/36013
I agree with mwigdahl, this is bad way of doing things, but this is the answer you seek:
declare #text VARCHAR(MAX)
set #text='[Dim Company].[Company].[23]'
SELECT SUBSTRING(#Text,
LEN('[Dim Company].[Company].[')+1,
LEN(#text)-LEN('[Dim Company].[Company].[')-1)
A better approach is to use the PARSENAME() function. The function's purpose is actually to parse an object name, such as server.schema.table, but since your string looks just like that, we can hijack the function. It's far more efficient, and cleaner than charindex/substring.
declare #text varchar(max), #p1 varchar(max), #p2 varchar(max), #p3 varchar(max)
set #text='[Dim Company].[Company].[23]'
set #p1 = PARSENAME(#text, 3)
set #p2 = PARSENAME(#text, 2)
set #p3 = PARSENAME(#text, 1)
select #p1, #p2, #p3

t-sql replace on text field

I have hit a classic problem of needing to do a string replace on a text field in an sql 2000 database. This could either be an update over a whole column or a single field I'm not fussy.
I have found a few examples of how to use updatetext to achieve it but they tend to be in stored procedures, does anyone know of a similar thing that is wrapped into a function so I can use it like I would usually use Replace(). The problem with the Replace() function for anyone who isn't aware is that it doesn't support text fields.
Edit: I realised I could probably get away with varchar(8000) so have swapped the fields to this type which fixes the issue. I never found a true solution.
Here is the sample query to update table with text column using REPLACE function. Hope this is useful for you.
UPDATE <Table> set textcolumn=
REPLACE(SUBSTRING(textcolumn,1,DATALENGTH(textcolumn)),'findtext','replacetext')
WHERE <Condition>
I am afraid you cannot do it within a function
When you try to declare a function like:
create function dbo.textReplace(
#inText as text)
returns text
as
begin
return 'a' -- just dummy code
end
You will get the following error:
The text data type is invalid for return values.
In other words you could not write a simple equivalent of REPLACE function for the text data type
This is my code snippet for this scenario:
DECLARE #oldtext varchar(1000)
DECLARE #newtext varchar(1000)
DECLARE #textlen int
DECLARE #ptr binary(16)
DECLARE #pos int
DECLARE #id uniqueidentifier
SET #oldtext = 'oldtext'
SET #newtext = 'newtext'
SET #textlen = LEN(#oldtext)
DECLARE mycursor CURSOR LOCAL FAST_FORWARD
FOR
SELECT [UniqueID]
,TEXTPTR([Text])
,CHARINDEX(#oldtext, [Text]) - 1
FROM [dbo].[myTable]
WHERE [Text] LIKE '%' + #oldtext +'%'
OPEN mycursor
FETCH NEXT FROM mycursor into #id, #ptr, #pos
WHILE ##fetch_status = 0
BEGIN
UPDATETEXT [dbo].[myTable].Text #ptr #pos #textlen #newtext
FETCH NEXT FROM mycursor into #id, #ptr, #pos
END
CLOSE mycursor
DEALLOCATE mycursor
You would have to cast the text field to a varchar(8000) or nvarchar(4000) if you are replacing over an ntext field.
MyField = REPLACE(CAST(MyField as VARCHAR(4000)), "string1", "string2")
This ofcourse will only work if you can guarantee the content in the field is <= 4000/8000 characters in length.
You can also use the SUBSTRING() function, which returns a varchar when passed a text value.
For instance:
MyVarchar = SUBSTRING(myTextField, 1, DATALENGTH(myTextField))
If you're populating a varchar with a specific length, you can truncate to fit:
MyVarchar100 = SUBSTRING(myTextField, 1, 100)

Resources