views:

2900

answers:

3

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?

A: 

According to the Sqlite SQL and UPDATE documentation, no. Sqlite has a limited SQL syntax.

duffbeer703
+7  A: 

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/%";
Logan
+3  A: 

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);
Bill Karwin
Good points, but unfortunately sqlite doesn't have real support for Foreign key enforcement.
foobar
Okay then you can't declare the foreign keys, but it's still better to break apart the slash-separated string into a normalized table.
Bill Karwin
You're right, and I was about to do so until it hit me that all I was doing was entirely unnecessary.The post I marked answered my question as I asked it, but if there was support for such, I'd have marked this as "supportive" or what have you. I did mod it up however...
foobar
Thanks, no worries it's all about sharing information. The rep points and stuff are secondary. :-)
Bill Karwin