How to update the field value of specific's column in SQL Server using Query in one shot? - sql-server

I have Imported Data Form XLS my CMS. but finally realize that it has wrong data without any Extension at the end of the data, in One of the column of the table, so now I want to change the column data of multiple rows based on specific ID? How to do that using single SQL Query?
I just want to add '.jpg' at the end on these data.
Image

UPDATE a
SET a.Imagepath = a.ImagePath + '.jpg'
FROM aspx_itemimages a
WHERE a.ItemId = yourid

Try this one -
UPDATE aspx_itemimages
SET ImagePath = ImagePath + '.jpg'
--WHERE itemid = 755

Try:
UPDATE ImagePath SET ImagePath = ImagePath + '.jpg'

According to your screenshot, some entries actually do end with .jpg. If you want to append .jpg only where it is absent, you could use a NOT LIKE predicate:
UPDATE aspx_itemimages
SET ImagePath = ImagePath + '.jpg'
WHERE ImagePath NOT LIKE '%.jpg'
;
That will also prevent you from adding the extension multiple times if you run the query again accidentally.

The above answers are correct but adding 2 strings returns 0, you will have to concat two strings.
here is the example:
UPDATE a
SET a.Imagepath = concat(ImagePath , '.jpg')
FROM aspx_itemimages a
WHERE a.ItemId = yourid

Best and Easiest way to do this...
"UPDATE aspx_itemimages
SET itempath = itempath +'.jpg'
WHERE itemid = 755 ";
Note: The Update doesn't generate a result set. If you want to know which records will be modified, first run a Select query that uses the same criteria. If the results are satisfactory, then run the update query.

Related

how can I add datetime stamp to zip file when unload data from snowflake to s3?

I want to be able to add a timestamp the filename I'm writing to s3. So far I've been able to write files to AWS S3 using example below. Can someone guide me as to how do I go about putting datetime stamp in the file name?
copy into #s3bucket/something.csv.gz
from (select * from mytable)
file_format = (type=csv FIELD_OPTIONALLY_ENCLOSED_BY = '"' compression='gzip' )
single=true
header=TRUE;
Thanks in advance.
The syntax for defining a path inside of a stage or location portion of the COPY INTO statement does not allow for functions to dynamically define it in SQL.
However, you can use a stored procedure to accomplish building dynamic queries, using JavaScript Date APIs and some string formatting.
Here's a very trivial example for your use-case, with some code adapted from another question:
CREATE OR REPLACE PROCEDURE COPY_INTO_PROCEDURE_EXAMPLE()
RETURNS VARIANT
LANGUAGE JAVASCRIPT
EXECUTE AS CALLER
AS
$$
var rows = [];
var n = new Date();
// May need refinement to zero-pad some values or achieve a specific format
var datetime = `${n.getFullYear()}-${n.getMonth() + 1}-${n.getDate()}-${n.getHours()}-${n.getMinutes()}-${n.getSeconds()}`;
var st = snowflake.createStatement({
sqlText: `COPY INTO '#s3bucket/${datetime}_something.csv.gz' FROM (SELECT * FROM mytable) FILE_FORMAT=(TYPE=CSV FIELD_OPTIONALLY_ENCLOSED_BY='"' COMPRESSION='gzip') SINGLE=TRUE HEADER=TRUE;`
});
var result = st.execute();
result.next();
rows.push(result.getColumnValue(1))
return rows;
$$
To execute, run:
CALL COPY_INTO_PROCEDURE_EXAMPLE();
The above is missing perfected date format handling (zero padding months, days, hours, minutes, seconds), error handling (if the COPY INTO fails), parameterisation of input query, etc. but it should give a general idea on how to achieve this.
As Sharvan Kumar suggests above, Snowflake now support this:
-- Partition the unloaded data by date and hour. Set ``32000000`` (32 MB) as the upper size limit of each file to be generated in parallel per thread.
copy into #%t1
from t1
partition by ('date=' || to_varchar(dt, 'YYYY-MM-DD') || '/hour=' || to_varchar(date_part(hour, ts))) -- Concatenate labels and column values to output meaningful filenames
file_format = (type=parquet)
max_file_size = 32000000
header=true;
list #%t1
This features is not supported yet in snowflake, however will be coming soon.

SQL Server - add to this query to first check for existence of a string

I have an nvarchar field in my database called CatCustom which contains comma-separated 5-character codes. It can contain as little as one code, or as many as 20 codes, separated by commas.
Right now, I use this query to add a new 5-character code to the field in given records (in this case the new code is LRR01):
UPDATE dbo.Sources
SET CatCustom = CONCAT_WS(', ', RTRIM(CatCustom), 'LRR01')
WHERE SourceID IN (1,2,3,4,5,8,9,44,63,45,101,102,222,344)
I need to add to this though: I need the record to be updated only if that 5-character code doesn't already exist somewhere in the CatCustom field, to ensure that code is not in there more than once.
How would I accomplish this?
EDIT: I really don't understand how this can be considered a duplicate of the suggested thread. This is a VERY specific case and has nothing to do with creating stored procedures and or variables. The alleged duplicated thread does not really help me - sorry.
Use STRING_SPLIT function to split the comma separated list and then add Not Exist condition in the WHERE clause like below
UPDATE dbo.Sources
SET CatCustom = CONCAT_WS(', ', RTRIM(CatCustom), 'LRR01')
WHERE SourceID IN (1,2,3,4,5,8,9,44,63,45,101,102,222,344)
AND NOT EXISTS (SELECT 1 FROM STRING_SPLIT(CatCustom, ',') where value = 'LRR01')
UPDATE dbo.Sources
SET
CatCustom = CONCAT_WS(', ', RTRIM(CatCustom), 'LRR01')
WHERE
SourceID IN (1,2,3,4,5,8,9,44,63,45,101,102,222,344)
AND CatCustom NOT LIKE '%LRR01%';

Updating XML value within MSSQL

replacing XML tag value within a large XML text value MSSQL.
Within MSSQL I have a column called form which is a text column with an extremely large XML. I need to find a certain tag and change the value of that sub tag within the tag from False to True.
This is what I currently have:
USE trainset;
UPDATE dbo.users
SET formxml = REPLACE(CAST(formxml as nvarchar(max)), '%<ttaycheckbox><name>cbTermsConditions</name><cargo>F</cargo></ttaycheckbox>%', '<ttaycheckbox><name>cbTermsConditions</name><cargo>T</cargo></ttaycheckbox>')
WHERE usersid = '0000GARX'
and formname ='ffOrderRpt'
and formxml LIKE ('%<ttaycheckbox><name>cbTermsConditions</name><cargo>F</cargo></ttaycheckbox>%')
It seems like it is doing the update;
However, after this when I do a select on this particular value the value of is still False rather than True.
What am I missing in there that is not causing it to update properly?
replace() doesn't support wildcards. So your where ... like finds the relevant records, but replace finds NOTHING, because it's looking for a literal %.
You can use XML modify and exist:
UPDATE users
SET formxml.modify('replace value of (/ttaycheckbox/cargo/text())[1] with "T"')
WHERE usersid = '0000GARX'
and formname ='ffOrderRpt'
and formxml.exist('/ttaycheckbox/name[text()[1] eq "cbTermsConditions"]') = 1
and formxml.exist('/ttaycheckbox/cargo[text()[1] eq "F"]') = 1

UPDATE only a part of a string value in a column

I am new to t-sql. I have a column which stores values as url's. I want to change the first part of the url's (string), and replace only this part with another url. For example, [url//lsansps01/PMO/ITG0038 iSCOMBI Data Model Project] to [url2//lwazitest.lionsure.com/PMO/ITG0038 iSCOMBI Data Model Project]
This is my update query:
UPDATE dbo.RowUpdates
SET ProjectWorkspaceInternalHRef = REPLACE ProjectWorkspaceInternalHRef, url//lsansps01/, url2//lwazitest.lionsure.com/PMO/ITG0038 iSCOMBI Data Model Project
FROM RowUpdates
WHERE ProjectWorkspaceInternalHRef LIKE url
REPLACE uses () and not comma delimited parameters,
UPDATE dbo.RowUpdates
SET ProjectWorkspaceInternalHRef = REPLACE(ProjectWorkspaceInternalHRef, 'url//lsansps01/', 'url2//lwazitest.lionsure.com/PMO/ITG0038 iSCOMBI Data Model Project')
FROM RowUpdates
WHERE ProjectWorkspaceInternalHRef LIKE url
another questionable part is LIKE url for it to work there should be '%'+url+'%' or something similar.
You want to look at MSDN: REPLACE (Transact-SQL)
from the article:
REPLACE ( string_expression , string_pattern , string_replacement )
so you'd want to change your replace statement to (remember to use a quote (') around your strings):
UPDATE dbo.RowUpdates
SET ProjectWorkspaceInternalHRef =
REPLACE(ProjectWorkspaceInternalHRef, 'url//lsansps01/', 'url2//lwazitest.lionsure.com/PMO/ITG0038 iSCOMBI Data Model Project')
FROM RowUpdates
WHERE ProjectWorkspaceInternalHRef LIKE url
It's also worth looking at the list of String Functions (Transact-SQL) you get in SQL Server.
Replace() function will not give your expected results if #OldUrl text is found in the middle of the ProjectWorkspaceInternalHRef.
If you want to replace only the front bit, use RIGHT() (or SUBSTRING()) function after filtering them out with LEFT() function.
DECLARE #OldUrl VARCHAR(500) = 'YourOdlUrl',
#NewUrl VARCHAR(500) = 'YourNewUrl'
UPDATE dbo.RowUpdates
SET ProjectWorkspaceInternalHRef = #NewUrl +
RIGHT(ProjectWorkspaceInternalHRef, LEN(ProjectWorkspaceInternalHRef) - LEN(#OldUrl ))
WHERE LEFT(ProjectWorkspaceInternalHRef, LEN(#OldUrl )) = #OldUrl

SQL String not fetching data

I'm using sql server compact 4 and i have run into a little snag. I have a table named Counter where i store some information 0-2 and it checks the todays date in that table, grabs the CounterValue and put them into one variable each 0,1,2 and present itself as a counter. The next day the new data will have a new date and will present the same values in each variable.
So far so good, if i run the SQL query as follows
SELECT * FROM Counter WHERE Dateis = '21-05-2014'
It present the correct values but when i try the Select from Razor it nothing is executed and it's driving me bonkers.
var DateNow = DateTime.Now.ToString("dd-MM-yyyy");
var CaseCounter = db.Query("SELECT * FROM Counter WHERE Dateis ='DateNow'");
DateNow has the value of 21-05-2014, the same as the sql query i tested have but it does nothing. No data is presented. If i remove the WHERE data will be displayed but then i displays all Dates data and not the current date.
Am i missing something here?
Thanks in advance.
You need to actually patch in the value of the variable, rather than the name of the variable:
var DateNow = DateTime.Now.ToString("dd-MM-yyyy");
var CaseCounter = db.Query("SELECT * FROM Counter WHERE Dateis = '" + DateNow + "'");
Your original code is literally submitting this command to the DB:
SELECT * FROM Counter WHERE Dateis = 'DateNow'
So instead you need to close the string with the double-quote, then a concatenation operator (the + ) and then your variable, before concatenating the closing quote.

Resources