Question

Given a database field named "widget_ids", containing data like "67/797/124/" or "45/", where the numbers are slash separated widget_ids... how would you make an update statement with SQL that would say: "if the widget_ids of the row with id X contains the text "somenumber/" do nothing, otherwise append "somenumber/" to it's current value"

Can you do something like that with SQL, or more specifically, sqlite? Is that something that is better done in the program for some reason or is there support for "if-then" like syntax in SQL?

Was it helpful?

Solution

Updates are kind of like if-thens themselves, and there is also if-then support of some sort in most SQL implementations. A simple solution might be:

update <tablename>
  set widget_id = widget_id + "somenumber/"
  where row_id = X
    and widget_id not like "%/somenumber/%"
    and widget_id not like "somenumber/%";

OTHER TIPS

First, get rid of the symbol-separated list. Use another table, with one widget id per row.

CREATE TABLE ThingieWidgets (
  thingie_id INT REFERENCES Thingies,
  widget_id INT REFERENCES Widgets,
  PRIMARY KEY(thingie_id, widget_id)
);

Fill the table with values from the slash-separated list:

INSERT INTO ThingieWidgets (thingie_id, widget_id)
  VALUES (1234, 67), (1234, 797), (1234, 124);

Now you can test if Thingie 1234 references Widget 45:

SELECT * FROM ThingieWidgets
WHERE thingie_id = 1234 AND widget_id = 45;

You can try to insert and recover if there's a duplicate key error:

INSERT INTO ThingieWidgets (thingie_id, widget_id)
  VALUES (1234, 45);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top