libelle_operation field in table tblOperation is imported from an incomplete external file. This field contains in some cases a string ("PADDOCK" in this example) corresponding to a tblTiers.id_tiers.
Other fields in table tblOperation (id_tiers, id_type_operation and id_categorie_budget) are null and should be update with the default values (libelle_tiers, id_type_operation and id_categorie_budget).
Table tblTiers contains the default values for the most recurrent id_tiers ("PADDOCK" is one of them).
The structure of the database is :
Dataset for table tblTiers is:
Table tblOperation contains initially :
And should contain this after "PADDOCK" has be found in libelle_operation and id_tiers, libelle_tiers and id_categorie_budget set to default value accordingly to default values stored in table tablTiers.
What should be the correct SQL statment for achieving this result?
Appears a partial link is possible with id_compte. Use WHERE clause to provide additional criteria to associate records.
UPDATE tblOperation INNER JOIN tblTiers ON tblOperation.id_compte = tblTiers.id_compte
SET tblOperation.id_tiers = tblTiers.id_tiers, tblOperation.id_type_operation = tblTiers.id_type_operation, tblOperation.id_categorie_budget = tblTiers.id_categorie_budget
WHERE libelle_operation LIKE "*" & libelle_tiers & "*";
Related
I am trying YugaByte's Cassandra API (YCQL) and interested in using the JSONB data type extensions.
But I am having trouble both updating an attribute in an existing JSONB column as well as adding a new attribute to an existing JSONB column.
Is this supported in YugaByte? Here is what I tried:
Consider the following example whichhas have one row with a simple key and JSONB column.
cqlsh:k> CREATE TABLE T (key int PRIMARY KEY, value jsonb);
cqlsh:k> INSERT INTO T(key, value) VALUES(1, '{"author": "Charles", "title": "Hello World"}');
cqlsh:k> SELECT * FROM T;
key | value
-----+--------------------------------------------
1 | {"author":"Charles","title":"Hello World"}
(1 rows)
So far so good.
If I try to update an existing attribute inside the doc, I see the following error:
cqlsh:k> UPDATE T SET value->'author' = 'Bruce' WHERE key=1;
InvalidRequest: Error from server: code=2200 [Invalid query] message="SQL error: \
Invalid Arguments. Corruption: JSON text is corrupt: Invalid value.
If I try to add a new attribute into an existing JSONB attribute, I get the following error;
cqlsh:k> UPDATE T SET value->'price' = '10' WHERE key=1;
InvalidRequest: Error from server: code=2200 [Invalid query] message="SQL error: \
Execution Error. Could not find member:
Is this supported, and if so what is the correct syntax?
When updating a string value you must enclose the new value in double quotes inside the single quotes. For example:
cqlsh:k> UPDATE T SET value->'author' = '"Bruce"' WHERE key=1;
cqlsh:k> SELECT * FROM T;
key | value
-----+------------------------------------------
1 | {"author":"Bruce","title":"Hello World"}
(1 rows)
Regarding the second question on ability to add new attributes:
For UPDATE, currently (as of 1.1) YugaByte DB allows updating specific attributes if that attribute/field already exists, but does not allow addition of new attributes into an existing JSONB column. If you need to the latter, you need to read the old value into the app, and write the new json in its entirety.
This is somewhat related to this MySQL to update an XML attribute but this time I want to update the node value. I have the following XMLfragment which is in marcxml column:
<leader>00227nz a2200109n 4500</leader>
<controlfield tag="001">1</controlfield>
...
<controlfield tag="005">20091210091717.0</controlfield>
...
I want to update the controlfield value tag 001 such that it becomes a number based on a query. So like this:
<leader>00227nz a2200109n 4500</leader>
<controlfield tag="001">10</controlfield>
...
<controlfield tag="005">20091210091717.0</controlfield>
...
I have initially the following mysql query:
UPDATE auth_header SET marcxml = UpdateXML(marcxml, '//controlfield[#tag="001"]', CONCAT('<controlfield tag="001">', '10', '</controlfield>')) WHERE Extractvalue(marcxml, '//controlfield[#tag="001"]') ='169625';
The table is auth_header and it has authid as primary key (but I guess this does no matter) and it has marcxml column where the xml is stored. The query gives me '0 rows affected.' so it seems it does not work.
Thanks in advance and cheers!
Looking at the discussions here MySQL to update an XML attribute and mysql site https://dev.mysql.com/doc/refman/5.1/en/xml-functions.html#function_updatexml, the query:
UpdateXML(xml_target, xpath_expr, new_xml)
should do the trick.
The xml_target is marcxml in the question's case. The xpath_expr is '//controlfield[#tag="001"]' which is the node that needs editing. The new_xml is to concat , the digit desired, and the closing statement . And lastly, the where expression is also the same with xpath expression above.
Hence:
UPDATE auth_header SET marcxml = UpdateXML(marcxml, '//controlfield[#tag="001"]', CONCAT('<controlfield tag="001">', '10', '</controlfield>' )) WHERE Extractvalue(marcxml, '//controlfield[#tag="001"]') ='169625';
I have this form in C# with a listbox where I selected 4 items. Now I want to make single stored procedure using which I can find data from single table for all this selected item with single parameter.
As I am a beginner when it comes to SQL Server, I completely don't know this type of procedure
Thanks, but this is not my question's answer
I want a Single Stored Procedure for all Items which are selected in ListBox
Create Procedure procedureName
(
#ItemName varchar(50),
)
AS
BEGIN
(
Select * from item_master where item_name = #ItemName
)
END
by this Query i can find data for one ItemName, but i want for all selected Items in Listbox, even I don't know the C# code also,
so plz help me....
This is a very simple example that does what you want. You would not want to use hard-coded connection strings, especially in-line, and you would want error-handling, but I am going for as much clarity as possible. You would also probably want to make the column length greater than 50 characters, but I made it match your column definition.
Also, I would recommend a generic approach, passing keys (column names) and values, so as to be able to use it for any sort of criteria, but you asked that I keep it to exactly what you require, so I trimmed it down to the essential.
This example returns all the Employees with FirstName matching any in the list passed to the stored procedure (as a user-defined table type).
First, create a user-defined table type (to hold the values you want to pass to the stored procedure) in your SQL Server database as follows:
CREATE TYPE [dbo].[FilterValues] AS TABLE(
[Value] [varchar](50) NOT NULL,
PRIMARY KEY CLUSTERED
(
[Value] ASC
)
)
The stored procedure to return the Employees looks as follows (note that it has the user-defined table type as the type of the single parameter passed in):
CREATE PROCEDURE [dbo].[GetEmployees] (
#FirstNameFilterValues dbo.FilterValues READONLY
)
AS
BEGIN
SELECT * FROM Employees
INNER JOIN #FirstNameFilterValues fv ON fv.Value = Employees.FirstName;
END
That's the SQL Server side done. To call it from C#, you can create a DataTable with a single column matching the column name and populate it with the values you want. In this simple example, I populate it with two names, but it could be as many as you want.
var filterValuesDataTable = new DataTable();
filterValuesDataTable.Columns.Add(new DataColumn("Value", typeof(string)) { AllowDBNull = false });
filterValuesDataTable.Rows.Add("Frodo");
filterValuesDataTable.Rows.Add("Sam");
using (var connection = new SqlConnection("server=.;Initial Catalog=Test;Integrated Security=True;"))
{
connection.Open();
using (var command = connection.CreateCommand())
{
command.CommandText = "GetEmployees";
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue("#FirstNameFilterValues", filterValuesDataTable);
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
Console.WriteLine("{0} {1}", reader["FirstName"], reader["LastName"]);
}
reader.Close();
}
}
connection.Close();
}
Very similar to this question MySQL Dynamic Query Statement in Python
However what I am looking to do instead of two lists is to use a dictionary
Let's say i have this dictionary
instance_insert = {
# sql column variable value
'instance_id' : 'instnace.id',
'customer_id' : 'customer.id',
'os' : 'instance.platform',
}
And I want to populate a mysql database with an insert statement using sql column as the sql column name and the variable name as the variable that will hold the value that is to be inserted into the mysql table.
Kind of lost because I don't understand exactly what this statement does, but was pulled from the question that I posted where he was using two lists to do what he wanted.
sql = "INSERT INTO instance_info_test VALUES (%s);" % ', '.join('?' for _ in instance_insert)
cur.execute (sql, instance_insert)
Also I would like it to be dynamic in the sense that I can add/remove columns to the dictionary
Before you post, you might want to try searching for something more specific to your question. For instance, when I Googled "python mysqldb insert dictionary", I found a good answer on the first page, at http://mail.python.org/pipermail/tutor/2010-December/080701.html. Relevant part:
Here's what I came up with when I tried to make a generalized version
of the above:
def add_row(cursor, tablename, rowdict):
# XXX tablename not sanitized
# XXX test for allowed keys is case-sensitive
# filter out keys that are not column names
cursor.execute("describe %s" % tablename)
allowed_keys = set(row[0] for row in cursor.fetchall())
keys = allowed_keys.intersection(rowdict)
if len(rowdict) > len(keys):
unknown_keys = set(rowdict) - allowed_keys
print >> sys.stderr, "skipping keys:", ", ".join(unknown_keys)
columns = ", ".join(keys)
values_template = ", ".join(["%s"] * len(keys))
sql = "insert into %s (%s) values (%s)" % (
tablename, columns, values_template)
values = tuple(rowdict[key] for key in keys)
cursor.execute(sql, values)
filename = ...
tablename = ...
db = MySQLdb.connect(...)
cursor = db.cursor()
with open(filename) as instream:
row = json.load(instream)
add_row(cursor, tablename, row)
Peter
If you know your inputs will always be valid (table name is valid, columns are present in the table), and you're not importing from a JSON file as the example is, you can simplify this function. But it'll accomplish what you want to accomplish. While it may initially seem like DictCursor would be helpful, it looks like DictCursor is useful for returning a dictionary of values, but it can't execute from a dict.
I have a database that has stored values in a complicated, serialized array where one component is a string and another is the length of the characters of the string, in this format:
s:8:"test.com"
Where "s" holds the character length of the string in the quotations.
I would like to change the string from "test.com" to "testt.com", and I'm using the following statement in SQL:
UPDATE table SET row=(REPLACE (row, 'test.com','testt.com'))
However, this breaks the script in question, because it doesn't update the character length in the "s" preceding the string where "test.com" is stored.
I was wondering if there is a query I can use that would replace the string, and then also increment the value of this "s" preceding to where the replacement occurs, something like this:
UPDATE table SET row=(REPLACE (row, 's:' number 'test.com','s:' number+1 'testt.com'))
Does anyone know if this kind of query is even possible?
UPDATE table set row = concat('s:',length('testt.com'),':"testt.com"');
If you need to change exact string, then use exact query -
UPDATE table SET row = 's:9:"testt.com"' WHERE row = 's:8:"test.com"';
The string is a "serialized string".
If there are multiple strings to be replaced, it might be easier to create a script to handle this.
In PHP, it goes something like this:
$searchfor = serialize('test.com');
$replaceby = serialize('testt.com');
// strip last semicolon from serialized string
$searchfor = trim($searchfor,';');
$replaceby = trim($replaceby,';');
$query = "UPDATE table SET field = '$replaceby' WHERE field = '$searchfor';";
This way, you can create an exact query string with what you need.
Do fill in the proper code for db connection if necessary.