Re-arrange string contents - sql

I have a string like: (10.00+Age)power2
I want to change the string to: power(10.00+Age,2)
How is this possible with sql server 2008.?

This expression reconstructs your strings as described:
'power' + replace(my_column, ')power', ',') + ')'
See SQLFiddle demo

If the string is always in the format you show, you could do a simple replace
replace("(10+Age)power2",")power2",",2)")
Updated
DECLARE #ans VARCHAR(200)
SET #ans = 'power'+replace('(10+Age)power2',')power2',',2)')

Related

How to convert charater string to uniqueidentifier and use Stuff function?

I'm using function to generate the result. What am I facing now is I pass the ItemGuid as parameter and currently I am using STUFF to find the ItemCode and concatenate result. However I getting an error said that Conversion failed when converting from a character string to uniqueidentifier.
My current result before using STUFF:
From Date : 01-01-2021 to 31-03-2021 Item No: IN ('a70014a3-2e00-41f0-9c3e-6fb8c4f2ab60','26dd67c1-fe37-41fa-b8c5-ff033928a291')
My expected result:
From Date : 01-01-2021 to 31-03-2021 Item No: IN ('ITM001','ITM021')
Please see my fiddle. SQL Fiddle
Parameter used: SELECT[dbo].[func_ReportCriteria2]('2021-01-01','2021-03-31','''a70014a3-2e00-41f0-9c3e-6fb8c4f2ab60'',''26dd67c1-fe37-41fa-b8c5-ff033928a291''') AS 'RESULT 2'
--using STUFF
CREATE FUNCTION [dbo].[func_ReportCriteria2]
(#FromDate DateTime
,#ToDate DateTime
,#Item_List NVARCHAR(MAX)
)
RETURNS nvarchar(max)
AS
BEGIN
DECLARE #CRITERIA NVARCHAR(MAX)
DECLARE #sqlCommand NVARCHAR(MAX)
DECLARE #ItemResult NVARCHAR(MAX)
SET #sqlCommand = ''
IF(ISNULL(#Item_List,'') != '')
BEGIN
--find ItemCode and concatenate based on ItemGuid
--error occur here
SET #ItemResult = STUFF( (SELECT ',' + ItemCode
FROM Item
WHERE ItemGuid IN (#Item_List)
FOR XML PATH('')), 1, 1, '')
SET #sqlCommand = 'Item No: IN ('+ #ItemResult +') '
END
SET #CRITERIA = 'From Date : ' + CONVERT(NVARCHAR(19),#FromDate,105) + ' to ' + CONVERT(NVARCHAR(19),#ToDate,105)
+ CHAR(13)+CHAR(10) + #sqlCommand
RETURN #CRITERIA
END
Please check if this fit your need:
declare #FromDate CHAR(10) ,#ToDate CHAR(10), #Item_List nvarchar(MAX)
select
#FromDate = '2021-01-01',-- make sure to convert the DATE from the table to NVARCHAR using style 120
#ToDate = '2021-03-31',-- make sure to convert the DATE from the table to NVARCHAR using style 120
#Item_List = '''a70014a3-2e00-41f0-9c3e-6fb8c4f2ab60'',''26dd67c1-fe37-41fa-b8c5-ff033928a291'''
------------------ Solution --------------------
-- Important! No reason for scalar function! Use it inline your query directly
SELECT
N'From Date : ' + #FromDate + ' to ' + #ToDate + N' Item No: IN (' + STRING_AGG(''''+ItemName+'''',',') + N')'
FROM Item
WHERE ItemGuid in (
-- Your string includes quotes which we must clear befor CONVERT to GUIDE
SELECT REPLACE([value],'''','') FROM STRING_SPLIT(#Item_List, ',')
)
Note! concat input text to string might be NOT safe and NOT recommended. It has a potential to SQL Injection!
Note: You probably plan a dynamic query, which will SELECT data from the table using the above string, which you asked to build. In this case, this seems like "XY problem" since you probably do not need to build this string at all. You can use the same approach to split string input and execute a direct SELECT query from your table. If we knew what is your final requested result is, then we could help in this as well, but the approach is the same is above code
Try apply convert itemguid
Change WHERE ItemGuid IN (#ItemList)
To WHERE cast(ItemGuid as NVARCHAR(MAX)) IN (#ItemList)

SQL Server concat empty string (not null)

I am trying to concat the columns here but when I encounter a column with empty / blank string, the concat failed.
I need to do some formatting for each column with different data type, so I am not using the CONCAT function. Using the conventional way like
SELECT CONVERT(varchar, [Priority]) + '~' + CONVERT(varchar,[AP_type]) + '~' + [AP_Name] + '~'
FROM table
Any suggestions on how I can concat empty string ?
Results I am looking :
0~0~~~~In~In
Thanks.
Couple of things.
always best to specify the length when converting to varchar. For example varchar(50)
concat() will handle nulls as empty string and there is no need to convert. Oddly enough, char(0) creates the odd behavior.
Example
Declare #YourTable Table ([priority] varchar(50),[ap_type] varchar(50),[ap_name] varchar(50),[ap_par] varchar(50),[infoText] varchar(50),[TxtCame] varchar(50),[TxtWent] varchar(50))
Insert Into #YourTable Values
(0,0,'','','','In','In')
,(0,0,'','',null,'In','In') -- Has Null
,(0,0,'','',char(0),'In','In') -- Has Char(0) ... Truncates without NullIf()
Select NewString = concat(priority,'~',ap_type,'~',ap_name,'~',ap_par,'~',NullIf(infoText,char(0)),'~',TxtCame,'~',TxtWent)
from #YourTable
Returns
NewString
0~0~~~~In~In
0~0~~~~In~In
0~0~~~~In~In -- NullIf() was required to fix

Spiliting values in query SQL

I'm facing a problem right now.. what if the query itself contains code between bracket like foo and this foo is replaced with a declare-result value like #foo
when O want to print what's the container in #foo instead of 'foo' i should use '#foo' but sql reads it as '#foo' and ignores the # because it's between ' and '
In c# as usual, I do use "'"+#foo+"'" now in sql there's no ID for " so we use '
when i use '''+#foo+''' it does not read. although in c# we use something like \ between the brackets to get it done, sql does not read
What should I do in this case?
Image for the problem and query itself:
Sounds like you're wanting to escape single quotes.
To do this you need to double them up!
DECLARE #foo char(1);
SET #foo = 'A';
SELECT '''' As a_single_quote
, '''''' As a_pair_of_single_quotes
, '''' + 'TEST' + '''' As escaped_string
, '''' + #foo + '''' As with_a_variable

SQL UPPER only specific word

Does anyone know how I can change only a word in the varchar field in my database? They are formatted like "Cheese", "cheese", "CheesE". I want to change to them all to CHEESE, but I have other text in those fields as well. I was wondering if their was a way to single that word out and make it uppper.
Something like
update table
set field = Upper(cheese)+rest of field
Thanks
update table
set field = replace(field, 'cheese', 'CHEESE')
SQLFIddle demo
From your comments I can see the diference between substring and word.
It is possible to do this kind of 'word-centric' transformation using XML as a proxy format.
Try this...
DECLARE #pattern nvarchar(max) = 'cheese'
SELECT
converted =
cast('<a><i>' + REPLACE(field, ' ', '</i><i>') + '</i></a>' as xml)
.query(
'for $x in /a/i return
if (not( ($x) is (/a/i[last()])[1] )) then
if (data($x) = sql:variable("#pattern")) then
concat(upper-case($x), "")
else
concat($x, "")
else
if (data($x) = sql:variable("#pattern")) then
string(upper-case($x))
else
string(data($x))')
.value('.', 'nvarchar(max)')
FROM table
I'm sure that it's possible to do it by parsing the expression char-by-char but I wanted to try it with XML :)

SQL Replace string in path

How would I replace everything before "Test" with a blank? The amount of subfolders in front of "Test" may vary.
C:\aaa\bbb\test\ccc\ddd
I would like it to be:
test\ccc\ddd
Solution in MSSQL, if you're using another RDMBS I'm sure they have equivalent functions for PATINDEX/SUBSTRING.
DECLARE #Path VARCHAR(8000)
,#Find VARCHAR(128)
SET #Path = 'C:\aaa\bbb\test\ccc\ddd'
SET #Find = 'Test\'
SELECT SUBSTRING(#Path,PATINDEX('%'+#Find+'%',#Path),LEN(#Path))
http://sqlfiddle.com/#!3/d41d8/8576
You can get the index of the string Text in your String, and get a substring from there to the end.
This query should work in any SQL - you may add syntatic fixes if required. In Oracle it would be SUBSTR/INSTR for example.
SELECT SUBSTR(str, start_pos) final_str
FROM
(
SELECT 'C:\aaa\bbb\test\ccc\ddd' as str
, INSTR('C:\aaa\bbb\test\ccc\ddd', 'test', 1) as start_pos
FROM dual
)
/
SQL>
FINAL_STR
-------------
test\ccc\ddd