How to replace string in SQLite? - iphone

How to update table column having this:
/var/mobile/233KKFSDK3234/Documents/Page.jpg
and replace it with
/Documents/Page.jpg
in SQLite?
Note: All text, except /Documents/ is dynamic.

You have to read first the string and put it in to an nsstring and then generate newstring form the old one and then update in to db.
Here you have the objective c code for generate the new string. The db update you can doit with the other answers.
NSString *originalString = #"/var/mobile/233KKFSDK3234/Documents/Page.jpg";
NSRange documentsRage = [originalString rangeOfString:#"/Documents/"];
NSString *newString = [NSString stringWithString:[originalString substringWithRange:NSMakeRange(documentsRage.location, [originalString length]-documentsRage.location)]];
NSLog(#"newString:%#",newString);

UPDATE table SET column = IF(
POSITION('/Documents/' IN column),
RIGHT(column, (LENGTH(column) - POSITION('/Documents/' IN column) - LENGTH('/Documents/') + 1)),
column
)
If the pattern is found, only keep characters right of the occurrence; else, do nothing (keep old value).

Following worked for me:
UPDATE yourtable
SET yourfield = SUBSTR(yourfield,18);
..as stated by Bjoern on this question:
How to Update this data using SQL?

Do the string processing in ObjC and then Use this query.
update tablename set columnname = 'processedString' ;
Updated as per your requirement

Related

Merge Statement overwriting entire row if Matched

I am trying to update records in a Sql Server 2012 table by using a MERGE statement. I have my target table and my source staging table. When the ID field matches I want to replace the entire row with the matching row from the source, and if not, add the row to the table as a new row. I don't know what to write after update set (?) to achieve this. here is my code:
USE DataCompany
MERGE INTO MasterAddress ma
USING MasterAddressStaging ms
ON MasterAddress.ID = MasterAddressStaging.ID
WHEN MATCHED THEN
UPDATE SET (?)
WHEN NOT MATCHED THEN
INSERT (ID
,CompanyName
,CompanyNumber
,RegAddress_CareOf
,RegAddress_POBox
,RegAddress_AddressLine1
,RegAddress_AddressLine2
,RegAddress_PostTown
,RegAddress_County
,RegAddress_Country
,RegAddress_PostCode)
VALUES (ms.ID
,ms.CompanyName
,ms.CompanyNumber
,ms.RegAddress_CareOf
,ms.RegAddress_POBox
,ms.RegAddress_AddressLine1
,ms.RegAddress_AddressLine2
,ms.RegAddress_PostTown
,ms.RegAddress_County
,ms.RegAddress_Country
,ms.RegAddress_PostCode);
thanks for your help
USE DataCompany
MERGE INTO MasterAddress ma
USING MasterAddressStaging ms
ON ma.ID = ms.ID
WHEN MATCHED THEN
UPDATE SET ma.CompanyName = ms.CompanyName,
ma.CompanyNumber = ms.CompanyNumber,
ma.RegAddress_CareOf =ms.RegAddress_CareOf,
ma.RegAddress_POBox =ms.RegAddress_POBox,
ma.RegAddress_AddressLine1 = ms.RegAddress_AddressLine1,
ma.RegAddress_AddressLine2 = ms.RegAddress_AddressLine2,
ma.RegAddress_PostTown = ms.RegAddress_PostTown,
ma.RegAddress_County = ms.RegAddress_County,
ma.RegAddress_Country = ms.RegAddress_Country,
ma.RegAddress_PostCode = ms.RegAddress_PostCode
WHEN NOT MATCHED THEN
INSERT (ID
,CompanyName
,CompanyNumber
,RegAddress_CareOf
,RegAddress_POBox
,RegAddress_AddressLine1
,RegAddress_AddressLine2
,RegAddress_PostTown
,RegAddress_County
,RegAddress_Country
,RegAddress_PostCode)
VALUES (ms.ID
,ms.CompanyName
,ms.CompanyNumber
,ms.RegAddress_CareOf
,ms.RegAddress_POBox
,ms.RegAddress_AddressLine1
,ms.RegAddress_AddressLine2
,ms.RegAddress_PostTown
,ms.RegAddress_County
,ms.RegAddress_Country
,ms.RegAddress_PostCode);
See examples here

Edit text value in Postgresql

I have a text column which holds a json with very long values - actually HTML code.
{"first_key" : "a very long html", "second_key" : "another very long html"}
How can I easily delete the second_key and its vale?
You could use regex_replace, and hope that the second html doesn't contain a } character:
update MY_TABLE set text_column = regex_replace(text_column, ', "second_key": ".*\}"', '')
where my_column_id = '<whatever>';
You will have to tweak your regex to make this work. You can test it by doing a select with the same expression to see what you get.

Issue in converting a stored procedure to NSString

In an iPhone App I've written, I connect to a web service for executing SQL Server stored procedures. I sent some simple queries, it works fine.
I tried some simple stored procedures, yes, again it works well. The issue is with this particular stored procedure's conversion to NSString. I realize am missing adding an escape character for some specific character. I've added escape characters for square brackets '[]', and for '%'. Am saying that escape characters is the issue because the error am getting after execution is saying 'syntax error in the stored procedure'.
But when I execute this directly in the DB (i.e. locally through SQL command-line client), am not getting any error ... it works fine. So, seems to be an issue when converting it to NSString. Please help.
DECLARE #ts_now bigint = (SELECT cpu_ticks/(cpu_ticks/ms_ticks) FROM sys.dm_os_sys_info);
SELECT TOP(10) SQLProcessUtilization AS \\[SQL Server Process CPU Utilization\\],
SystemIdle AS \\[System Idle Process\\],
100 - SystemIdle - SQLProcessUtilization AS \\[Other Process CPU Utilization\\],
DATEADD(ms, -1 * (#ts_now - \\[timestamp\\]), GETDATE()) AS \\[Event Time\\]
FROM (
SELECT record.value('(./Record/#id)\\[1\\]', 'int') AS record_id,
record.value('(./Record/SchedulerMonitorEvent/SystemHealth/SystemIdle)\\[1\\]', 'int')
AS \\[SystemIdle\\],
record.value('(./Record/SchedulerMonitorEvent/SystemHealth/ProcessUtilization)\\[1\\]',
'int')
AS \\[SQLProcessUtilization\\], \\[timestamp\\]
FROM (
SELECT \\[timestamp\\], convert(xml, record) AS \\[record\\]
FROM sys.dm_os_ring_buffers
WHERE ring_buffer_type = N'RING_BUFFER_SCHEDULER_MONITOR'
AND record LIKE '%%<SystemHealth>%%') AS x
) AS y
ORDER BY record_id DESC;
Am getting an error saying the syntax is wrong. I read this stored procedure into a NSString object and then send the NSString to the web service like this :
NSError *error;
NSString *txtFilePath = [[NSBundle mainBundle] pathForResource:#"Proc_Usage" ofType:#"txt"];
NSString *procUsage = [NSString stringWithContentsOfFile:txtFilePath encoding:NSUTF8StringEncoding error:&error];
if (procUsage == nil) {
return -1;
}
[[DbConnect DbConnect_Singleton] executeInDb:procUsage];
Have you tried it without any escaping at all? I don't see why it should need any escaping at all, given that you are reading the string from a file - it's not like it's a string literal.
It's possible that the double percents are being read as a single percent. Can you try changing:
LIKE '%%<SystemHealth>%%'
to
LIKE '%%%%<SystemHealth>%%%%'

How to run SQLite Query even if Input is Blank

I am doing an iPad project, there are 3 tables in UI. if i select row in each table. Sqlite query will take the value from table and run the query. please find my Query below.
NSString * str3=tableFou.string4;
NSString * str4=tableFiv.string5;
NSString * str2=tablethr.string3;
sqlite3 *database;
favorite=[[NSMutableArray alloc]init];
if(sqlite3_open([databasePath UTF8String], &database)== SQLITE_OK){
NSString *sql=[NSString stringWithFormat:#"Create view prizeview as SELECT country.name,item_country.id,text.text,substr(text,1,2) FROM country,item_country,prize,item_prize,gender,item_gender,text WHERE country.name = '%#' AND text.item = item_country.item AND country.id = item_country.id AND prize.name = '%#' and text.item=item_prize.item and prize.id = item_prize.id and gender.name = '%#' and text.item=item_gender.item and gender.id = item_gender.id ",str3,str4,str2];
const char *sqlStatement = [sql UTF8String];;
problem is that, the query is running if i select all the tables only.. but i want results if i select even one table. how can i do that?
Try with if condition use with and condition and pass all your str in if condition only.
use your if condition like this.
if(([propertyTypeLabel.text length]==0) || ([cityLabel.text length]==0 ) ||( [locationLabel.text length]==0 )|| ([priceLabel.text length] ==0)||([postedLabel.text length]==0))
In this like any of text is zero condition true you also use if ant of the table cell is tap your query run.
You can't search for empty fields unless the field is actually empty. F.ex. if you search
select * from mytable where username = "";
You won't find it, but if you are ok with the field being empty or whatever result, you must use like instead of =
select * from mytable where username like "%";
or better yet, you can create your query like this, lets say you have three fields to search for, username, firstname and lastname. The code below needs a few more if's and buts, but you should be able to make this work and only add the parameters to where if they fulfill the requirements.
NSMutableString *query = [[NSMutableString alloc] init];
[query appendString:#"select * from table where "];
if (username.text.lenghth >1) [query appendString:[NSString stringWithFormat:#"username = '%#'"]];
if (firstname.text.length >1) [query appendString:[NSString stringWithFormat:#"&& firstname = '%#'"]];
if (lastname.text.length >1) [query appendString:[NSString stringWithFormat:#"&& lastname = '%#'"]];
Hope this helps

iphone sqlite3_column_text issue

I have a column in sqlite3 table. Column has values like
1 ½”
1 ¾”
2 ½” etc.
Column has VARCHAR datatype.
I am using this code.
pref_HoseDiameter = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
Now, when I am fetching these values from database, I am getting pref_HoseDiameter string values like this:
1 1/2"
1 3/4"
2 1/2"
How to fetch those values as they are in database or how to convert them that look like database values.
Help would be appreciated.
Thanks in advance.
Try to use sqlite3_column_text16 to get the string as UTF-16, then create the string with +stringWithCharacters:.
const UInt16* text = sqlite3_column_text16(statement, column);
int text_len = // find the first 0x0000 in text;
NSString* str = [NSString stringWithCharacters:text length:text_len];