0

I need to be able to add a set of values into a table every time a new user is added into my system.

When the user is added, I want to look into my 'Tags' table, and insert a new entry into the 'Tag_Score' table for each of the IDs in the 'Tags' table.

I tried the following based on something i found online but although the logic seems sound, it doesn't seem to be working

DECLARE @LoopVar INTEGER
SET @LoopVar = ( SELECT MIN(Tag_Score.T_ID) 
FROM Tags ) WHILE @LoopVar IS NOT NULL 
BEGIN 
INSERT INTO  `a3360218_DD`.`Tag_Score` (
`A_ID` ,
`T_ID` ,
`Score` ,
`Visits`
)
VALUES (
'" . $accountID . "', @LoopVar ,  '0',  '0'
)
SET @LoopVar = ( SELECT MIN(Tag_Score.T_ID) 
FROM TheTable
WHERE @LoopVar < T_ID ) 
END

The error given is:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHILE @LoopVar IS NOT NULL 
BEGIN 
INSERT INTO  `a3360218_DD`.`Tag_Score` (

' at line 2 

Thanks in advance

Matt

Clodoaldo Neto
  • 118,695
  • 26
  • 233
  • 260
  • It would really help if you explained a bit more *in English* what it is you're trying to do, rather than posting broken code (although it's good you tried something). Also, please post table definitions of `Tags` and `Tag_Score` – Bohemian Apr 04 '12 at 15:40
  • I am struggling to understand your question but it sounds like you need to look at [INSERT... SELECT](http://dev.mysql.com/doc/refman/5.5/en/insert-select.html) – user1191247 Apr 04 '12 at 15:43
  • Sorry i've had a pretty long day, just re-read this and you're both right, my english is terrible haha! This INSERT...SELECT stuff seems to be the right way though, i'd never heard of it before (kinda new to this all). Thanks a lot guys – Matthew Albone Apr 04 '12 at 16:34

2 Answers2

3

You haven't posted any table layouts, so I'm shooting in the dark here, but this kind of query should work for you:

INSERT INTO Tag_Score (A_ID, T_ID, Score, Visits)
SELECT A_ID, T_ID, 0,  0
FROM Tags
WHERE A_ID = $accountID;

Note the removal of all those unnecessary back-ticks (ie `) that are only necessary when you have a schema name that is a reserved word, and look how readable it is now!

Keep things simple - avoid complex SQL if you can.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

I think you might want CROSS JOIN, or maybe just a regular insert from...

insert into Tag_Score
select accountID, t.ID, 0, 0
from tags t
-- optional order by
-- order by t.ID 
Chris Gessler
  • 22,727
  • 7
  • 57
  • 83