String update in SQL Server - sql

Currently I have varchar field. The delimiter is "$P$P$".
The delimiter will appear at least once and at most twice in the varchar data.
Eg.
Sample Heading$P$P$Sample description$P$P$Sample conclusion
Sample Heading$P$P$Sample Description
If the delimiter appears twice, I need to insert a text before the second occurance of the delimiter.
Eg:
Sample Heading$P$P$Sample DescriptionINSERT TEXT HERE$P$P$Sample Conclusion
If the delimiter occurs only once, then I need to insert a text at the end of the field.
Eg:
Sample Heading$P$P$Sample DescriptionAPPEND TEXT HERE
How this can be done in SQL query?

If you are going to do a lot of string manipulation you might want to use a CLR (.net) function. Since SQL Server isn't exactly made for string manipulation.
Or even better, pull this data back to your application and do it in code.
I even think you can't do it using the default SQL Server String functions

The CharIndex function has an optional 3rd parameter that allows you to specify the starting position of the search. You can use this to find the 2nd occurrence of a string using CharIndex. You can also use the stuff function to insert a string in to another string.
Example:
Declare #Temp Table(Data VarChar(8000))
Insert Into #Temp Values('Sample Heading$P$P$Sample description$P$P$Sample conclusion')
Insert Into #Temp Values('Sample Heading$P$P$Sample Description')
Select len(Data),
CharIndex('$P$P$', Data + '$P$P$',CharIndex('$P$P$',Data) + 1),
Stuff(Data + ' ', CharIndex('$P$P$', Data + '$P$P$',CharIndex('$P$P$',Data) + 1), 0, 'Text Here')
From #Temp
I realize it looks like a mess, but I do encourage you to understand how this works because you may need something similar in the future.

instead of using delimiters, why not creating 3 columns or if you only want one --> an xml field?

Related

SQL Wildcard within data

My situation is a bit odd. I have generated filenames inserted into a database that are to be matched with downloaded files later, however the downloaded files contain a random ID in the middle of their name.
If I include the wildcard characters on the generated filename that's inserted into the database, is there anyway to compare that against the actual downloaded file?
Generated name example: just-a-file-name-and-a-suffix.mp4
Actual downloaded file: just-a-file-name-51935-and-a-suffix.mp4
I have zero way to actually know what those 5 digits will be. I only know that there will be 5 digits. Ideally I'd insert the generated name into the database something like just-a-file-name-%-and-a-suffix.mp4 and use the LIKE keyword in a SQL query but it doesn't work that way.
Is there anything I can do to solve this and get a match?
you can use substring, replace and some other functions if you like.
Following is an example of using replace and creating a function for it.
`
CREATE Function [dbo].[RemoveNumericCharacters](#Temp VarChar(1000))
Returns VarChar(1000)
AS
Begin
Declare #NumRange as varchar(50) = '%[0-9]%'
While PatIndex(#NumRange, #Temp) > 0
Set #Temp = Stuff(#Temp, PatIndex(#NumRange, #Temp), 1, '')
Return #Temp
End
and you can use it like so
SELECT dbo.RemoveNumericCharacters FROM TARGET_TABLE
`
taken from following post -- Remove numbers from string sql server
Note you be passing on your file string to the function and it will return the file name without the numbers in it.
Thanks

Grafana - SQL 2014 - MSSQL - How to insert the result of a variable templating in a table

I want to rework a result of templating variable that looks like this:
'string1','string2','string3'
I try to add few characters like 'test', before every string.
In fact if I could just get a way to insert all these strings in a table I would be fine but I fail at this step.. BTW It must work for n string in the result.
Ideal result would be:
select *
From tbl
returning this (I don't care if column as a title):
colName
'teststring1'
'teststring2'
'teststring3'
but just beeing able to insert it in a table would be nice I'll handle the update of the strings.
If your string is like 'string1,string2,string3' and working with the higher version of SQL Server then you can try the following way.
declare #string as varchar(120) = 'string1,string2,string3'
select
'test' + value
from string_split (#string, ',')
Here is the live db<>fiddle demo.

SQL Server - Adding a string to a text column (concat equivalent)

How do you add a string to a column in SQL Server?
UPDATE [myTable] SET [myText]=' '+[myText]
That doesn't work:
The data types varchar and text are incompatible in the add operator.
You would use concat on MySQL, but how do you do it on SQL Server?
like said before best would be to set datatype of the column to nvarchar(max), but if that's not possible you can do the following using cast or convert:
-- create a test table
create table test (
a text
)
-- insert test value
insert into test (a) values ('this is a text')
-- the following does not work !!!
update test set a = a + ' and a new text added'
-- but this way it works:
update test set a = cast ( a as nvarchar(max)) + cast (' and a new text added' as nvarchar(max) )
-- test result
select * from test
-- column a contains:
this is a text and a new text added
Stop using the TEXT data type in SQL Server!
It's been deprecated since the 2005 version. Use VARCHAR(MAX) instead, if you need more than 8000 characters.
The TEXT data type doesn't support the normal string functions, while VARCHAR(MAX) does - your statement would work just fine, if you'd be using just VARCHAR types.
The + (String Concatenation) does not work on SQL Server for the image, ntext, or text data types.
In fact, image, ntext, and text are all deprecated.
ntext, text, and image data types will
be removed in a future version of
MicrosoftSQL Server. Avoid using these
data types in new development work,
and plan to modify applications that
currently use them. Use nvarchar(max),
varchar(max), and varbinary(max)
instead.
That said if you are using an older version of SQL Server than you want to use UPDATETEXT to perform your concatenation. Which Colin Stasiuk gives a good example of in his blog post String Concatenation on a text column (SQL 2000 vs SQL 2005+).
UPDATE test SET a = CONCAT(a, "more text")
hmm, try doing CAST(' ' AS TEXT) + [myText]
Although, i am not completely sure how this will pan out.
I also suggest against using the Text datatype, use varchar instead.
If that doesn't work, try ' ' + CAST ([myText] AS VARCHAR(255))
To Join two string in SQL Query use function CONCAT(Express1,Express2,...)
Like....
SELECT CODE, CONCAT(Rtrim(FName), " " , TRrim(LName)) as Title FROM MyTable

SQL Server - Replacing Single Quotes and Using IN

I am passing a comma-delimited list of values into a stored procedure. I need to execute a query to see if the ID of an entity is in the comma-delimited list. Unfortunately, I think I do not understand something.
When I execute the following stored procedure:
exec dbo.myStoredProcedure #myFilter=N'1, 2, 3, 4'
I receive the following error:
"Conversion failed when converting the varchar value '1, 2, 3, 4' to data type int."
My stored procedure is fairly basic. It looks like this:
CREATE PROCEDURE [dbo].[myStoredProcedure]
#myFilter nvarchar(512) = NULL
AS
SET NOCOUNT ON
BEGIN
-- Remove the quote marks so the filter will work with the "IN" statement
SELECT #myFilter = REPLACE(#myFilter, '''', '')
-- Execute the query
SELECT
t.ID,
t.Name
FROM
MyTable t
WHERE
t.ID IN (#myFilter)
ORDER BY
t.Name
END
How do I use a parameter in a SQL statement as described above? Thank you!
You could make function that takes your parameter, slipts it and returns table with all the numbers in it.
If your are working with lists or arrays in SQL Server, I recommend that you read Erland Sommarskogs wonderful stuff:
Arrays and Lists in SQL Server 2005
You need to split the string and dump it into a temp table. Then you join against the temp table.
There are many examples of this, here is one at random.
http://blogs.microsoft.co.il/blogs/itai/archive/2009/02/01/t-sql-split-function.aspx
Absent a split function, something like this:
CREATE PROCEDURE [dbo].[myStoredProcedure]
#myFilter varchar(512) = NULL -- don't use NVARCHAR for a list of INTs
AS
SET NOCOUNT ON
BEGIN
SELECT
t.ID,
t.Name
FROM
MyTable t
WHERE
CHARINDEX(','+CONVERT(VARCHAR,t.ID)+',',#myFilter) > 0
ORDER BY
t.Name
END
Performance will be poor. A table scan every time. Better to use a split function. See: http://www.sommarskog.se/arrays-in-sql.html
I would create a function that takes your comma delimited string and splits it and returns a single column table variable with each value in its own row. Select that column from the returned table in your IN statement.
I found a cute way of doing this - but it smells a bit.
declare #delimitedlist varchar(8000)
set #delimitedlist = '|1|2|33|11|3134|'
select * from mytable where #delimitedlist like '%|' + cast(id as varchar) + '|%'
So... this will return all records with an id equal to 1, 2, 33, 11, or 3134.
EDIT:
I would also add that this is not vulnerable to SQL injection (whereas dynamic SQL relies on your whitelisting/blacklisting techniques to ensure it isn't vulnerable). It might have a performance hit on large sets of data, but it works and it's secure.
I have a couple of blog posts on this as well, with a lot of interesting followup comments and dialog:
More on splitting lists
Processing list of integers

Accessing text fields in a stored procedure and insert to another table

I am trying to access a “text” type and inserting that value into another table viw a stored procedure. I’ve tried to cast it, convert it, but nothing works.
My code looks somethings like this:
Declare #Critique varchar(max), #Feedback varchar(max)
…
…
…
SELECT #Critique = CAST(comments as varchar(max)), #Feedback = CAST(public_critique as varchar(max)) FROM ASCO_vEXTERNAL_REVIEW_APPLICATIONS_LIST WHERE wf_task_assignment_id = #WfTaskAssignmentIDP1
– comments and public_critique are defined as text in view (also tried with table) ASCO_vEXTERNAL_REVIEW_APPLICATIONS_LIST
…
…
…
insert into WF_TASK_ASSIGNMENT_REVIEW (wf_task_assignment_review_id, wf_task_assignment_id, grantee_project_id, comments, public_critique) values (#NewID1, #WfTaskAssignmentIDP2, #GranteeProjectID, #Critique, #Feedback)
Can you please help me with this as soon as possible. I would really appreciate this.
Thanks,
Harish
I'm assuming that the WF_TASK_ASSIGNMENT_REVIEW is the one containing the text column you're trying to write into.
The text type is now deprecated in SQL 2005 and 2008. If at all possible try and upgrade the WF_TASK_ASSIGNMENT_REVIEW table to use the nvarchar(max) type instead.
If not, the only way is to use the WRITETEXT statement to write into the target column, in a loop (since WRITETEXT has an upper limit). See the WRITETEXT statement example in the SQL Server docs.
Your question is not sound good to understand .
Dont use text ,it wont support in many cases like where ,group by etc , so try use varchar
This is just an example
Declare #Critique varchar(max)
set #Critique = (select public_critique from ASCO_vEXTERNAL_REVIEW_APPLICATIONS_LIST
where convert(varchar(50), wf_task_assignment_id ) =#WfTaskAssignmentIDP1)