How to query a condition on a single object of sql record? - sql

I'll try my best to explain the situation here. We are using Maria DB.
In certain case we are looping over all the records/rows of a REQUESTS table.
and for each object/record we are checking few conditions and if condition passes we are performing an action. All the said things here are being done using ruby. Say I want to check the same on pure SQL, I wanted to see how.
Sample Object a Request table:
[{"ot_rqst_id":27460354,"rqst_type_cd":"NONTP","svc_type_cd":"TD","sl_ttl_type_cd":"","lot_num":41843022, ttl_stg_cd: 'CMPLT'}]
What I want to check on sql:
To see if the ttl_stg_cd of this object is equal to 'CMPLT'. If it is then update it to NULL else "something_else".
Let me remind you again that, I am already doing this in ruby language, but I am not an expert on sql so help would be appreciated.

The following query should do what you want.
I have taken the id from your query string. You need to put in the real table name and check the WHERE clause. If you remove the WHERE clause it will update all records in the table, you may wish the change it to something like
WHERE column_X = value_Y
UPDATE table_name
SET ttl_stg_cd = CASE ttl_stg_cd
WHEN 'CMPLT' THEN null
ELSE 'something_else' END
WHERE ot_rqst_id = 27460354;

Related

Can I Search for a Specific Row and Update it?? Google BigQuery Question

I am new to BigQuery and was wondering if there was a way to search for a specific row, then individually update its columns using a Query. I am very new to database and SQL, and would love some of your help.
Yes you can. Typically this is achieved through data manipulation language (DML). For this specific example you would want use an UPDATE statement.
Documentation on this can be found here:
https://cloud.google.com/bigquery/docs/reference/standard-sql/dml-syntax#update_statement
As a word of caution verify your where clause before you execute to ensure you are targeting the correct rows.
For example:
UPDATE your_table
SET assigned_to_user = 'updated_value' -- the value you want to update to
WHERE -- this is where you define your criteria to narrow down to a subset of rows
criteria_column = 'target_values' -- this is your critera
-- and criteria_column_2 = 'other_value' -- if you need to expand more critiera just use logic operators like `and` or `or`
You can also test out what will be updated by issuing a select statement with the same criteria as your update and seeing which columns come back, for example:
select *
from your_table
WHERE
criteria_column = 'target_values'

Oracle Update table to set specific attribute value in semicolon separated values

I have a column where I have values like:
Email_Password+oi8hu907b;New_eMail+Y;Email_Username+iugbhijhb8
Now I want to update New_eMail attribute for all rows which has Y to N without affecting anything else.
Please advise.
i hate it but...
update table
set column = replace(column,'New_eMail+Y','New_eMail+N')
where column like '%New_eMail+Y%'
you don't need the WHERE clause but if you put a functional index on the table it may be quicker with it
Since it may be the only place in the string where '+Y;' occurs the following statement may do the trick:
update <your_table>
set <your_column> = replace(<your_column>,'+Y;','+N;')
where instr(<your_column>,'+Y;')>0
This solution differs from the others provided because it does not depend on the value of the email address.
My answer is a slight improvement over the answer from user davegreen100
Since they don't allow me to post it as a comment, I add it here.
update <<tablename>>
set <<columnname>> = replace(<<columnname>>,';New_eMail+Y;',';New_eMail+N;')
where <<columnname>> like '%;New_eMail+Y;%'

Structuring many update statements in SQL Server

I'm using SQL Server. I'm also relatively new to writing SQL... in a strong way. It's mostly self-taught, so I'm probably missing key ideas in terms of proper format.
I've a table called 'SiteResources' and a table called 'ResourceKeys'. SiteResources has an integer that corresponds to the placement of a string ('siteid') and a 'resourceid' which is an integer id that corresponds to 'resourceid' in ResourceKeys. ResourceKeys also contains a string for each key it contains ('resourcemessage'). Basically, these two tables are responsible for representing how strings are stored and displayed on a web page.
The best way to consistently update these two tables, is what? Let's say I have 5000 rows in SiteResources and 1000 rows in ResourceKeys. I could have an excel sheet, or a small program, which generates 5000 singular update statements, like:
update SiteResources set resoruceid = 0
WHERE siteid IS NULL AND resourceid IN (select resourceid
from ResourceKeys where resourcemessage LIKE 'FooBar')
I could have thousands of those singular update statements, with FooBar representing each string in the database I might want to change at once, but isn't there a cleaner way to write such a massive number of update statements? From what I understand, I should be wrapping all of my statements in begin/end/go too, just in-case of failure - which leads me to believe there is a more systematic way of writing these update statements? Is my hunch correct? Or is the way I'm going about this correct / ideal? I could change the structure of my tables, I suppose, or the structure of how I store data - that might simplify things - but let's just say I can't do that, in this instance.
As far as I understand, you just need to update everything in table SiteResources with empty parameter 'placement of a string'. If so, here is the code:
UPDATE a
SET resourceid = 0
FROM SiteResources a
WHERE EXISTS (select * from ResourceKeys b where a.resourceid = b.resourceid)
AND a.siteid IS NULL
For some specific things like 'FooBar'-rows you can add it like this:
UPDATE a
SET resourceid = 0
FROM SiteResources a
WHERE EXISTS (select * from ResourceKeys b where a.resourceid = b.resourceid and b.resourcemessage IN ('FooBar', 'FooBar2', 'FooBar3', ...))
AND a.siteid IS NULL
Let me see if I understood the question correctly. You'd like to update resourceid to 0 if the resourcemessage corresponds to a list of strings ? If so, you can build your query like this.
UPDATE r
SET resourceid = 0
FROM SiteResources r
JOIN ResourceKeys k ON r.resourceid = k.resourceid
WHERE k.resourcemessage IN ('FooBar', ...)
AND r.siteid IS NULL;
This is using an extended UPDATE syntax in transact-sql allowing you to use a JOIN in the UPDATE statement. But maybe it's not exactly what you want ? Why do you use the LIKE operator in your query, without wildcard (%) ?
With table-valued parameters, you can pass a table from your client app to the SQL batch that your app submits for execution. You can use this to pass a list of all the strings you need to update to a single UPDATE that updates all rows at once.
That way you don't have to worry about all of your concerns: the number of updates, transactional atomicitty, error handling. As a bonus, performance will be improved.
I recommend that you do a bit of research what TVPs are and how they are used.

Update table in run time and the column not known in compile time

I am trying to write the SQL to update multiple columns based on some code condition to the table in the code.
For example, make it the easiest one in two columns
UPDATE table set A = valueA where conditionA..
OR UPDATE table set B=valueB where conditionA..
OR UPDATE table set A=valueA, B=valueB where conditionA..
The condition is the same, but valueA/valueB may not exist depending on the code
Is there any convenient way to combine them together in one SQL such as the select one WHERE 1=1 and <condition> so that I can add the conditions regardless one or more than one conditions?
Hope it make sense.
if you use the same condition you can write the query simply like this:
UPDATE [table] SET A = valueA, B=valueB, C=valueC WHERE <condition>
But if you need different conditions for all the fields, you could you a CASE operator like this:
UPDATE [table] SET A = CASE WHEN <cond_for_A> THEN valA ELSE A END,
CASE WHEN <cond_for_B> THEN valB ELSE B END,
CASE WHEN <cond_for_C> THEN valC ELSE C END
You vary the fields being updated, presumably based on some condition in your code, which probably means you won't be able to get away with just one SQL statement - bound parameters cannot "add" or "remove" columns within SQL text.
If you have a small number of columns, you can make a separate SQL statement for each combination of them that is of interest. Otherwise, you'll likely need to construct the SQL text dynamically and fill the SET clause of your statement so it includes exactly the columns you need.
None of this should serve as an excuse to skip properly binding all parameters, though!

Dynamic Query in SQL Server

I have a table with 10 columns as col_1,col_2,.... col_10. I want to write a select statement that will select a value of one of the row and from one of these 10 columns. I have a variable that will decide which column to select from. Can such query be written where the column name is dynamically decided from a variable.
Yes, using a CASE statement:
SELECT CASE #MyVariable
WHEN 1 THEN [Col_1]
WHEN 2 THEN [Col_2]
...
WHEN 10 THEN [Col_10]
END
Whether this is a good idea is another question entirely. You should use better names than Col_1, Col_2, etc.
You could also use a string substitution method, as suggested by others. However, that is an option of last resort because it can open up your code to sql injection attacks.
Sounds like a bad, denormalized design to me.
I think a better one would have the table as parent, with rows that contain a foreign key to a separate child table that contains ten rows, one for each of those columns you have now. Let the parent table set the foreign key according to that magic value when the row is inserted or updated in the parent table.
If the child table is fairly static, this will work.
Since I don't have enough details, I can't give code. Instead, I'll explain.
Declare a string variable, something like:
declare #sql varchar(5000)
Set that variable to be the completed SQL string you want (as a string, and not actually querying... so you embed the row-name you want using string concatenation).
Then call: exec(#sql)
All set.
I assume you are running purely within Transact-SQL. What you'll need to do is dynamically create the SQL statement with your variable as the column name and use the EXECUTE command to run it. For example:
EXECUTE('select ' + #myColumn + ' from MyTable')
You can do it with a T-SQl CASE statement:
SELECT 'The result' =
CASE
WHEN choice = 1 THEN col1
WHEN choice = 2 THEN col2
...
END
FROM sometable
IMHO, Joel Coehoorn's case statement is probably the best idea
... but if you really have to use dynamic SQL, you can do it with sp_executeSQL()
I have no idea what platform you are using but you can use Dynamic LINQ pretty easily to do this.
var query = context.Table
.Where( t => t.Id == row_id )
.Select( "Col_" + column_id );
IEnumerator enumerator = query.GetEnumerator();
enumerator.MoveNext();
object columnValue = enumerator.Current;
Presumably, you'll know which actual type to cast this to depending on the column. The nice thing about this is you get the parameterized query for free, protecting you against SQL injection attacks.
This isn't something you should ever need to do if your database is correctly designed. I'd revisit the design of that element of the schema to remove the need to do this.