1

I have really annoying problem. I have this query that I am sending from c# project. Problem is that I cannot succeed to use value from another table into my insert. Here is my sample of code:

INSERT Izdavanje (registracioniBrojKorisnika, imeKorisnika, identifikacioniBrojKnjige, vremeidatumIzdavanja) 
  VALUES (@rbKorisnika, 
         (SELECT imeKorisnika 
            FROM Korisnici 
           WHERE registracioniBrojKorisnika=@rbKorisnika),
          @idKnjige, 
         GetDate()); 
6
  • INSERT INTO t (c1, c2, ...) SELECT... Where you can select columns and literals etc (i.e. expressions.) Commented Oct 10, 2016 at 12:44
  • @jarlh But I wanna pull just 1 or 2 values from another table, not all of them. Commented Oct 10, 2016 at 12:46
  • One or two columns, or one or two rows? Commented Oct 10, 2016 at 12:48
  • @jarlh I wanna do insert with 2 values that are from c# (I can do that without problem, of course) and 2 column values from row that have specific ID. Commented Oct 10, 2016 at 12:50
  • 1
    Put those values in the SELECT, i.e. SELECT @rbKorisnika, imeKorisnika, @idKnjige... Commented Oct 10, 2016 at 12:52

2 Answers 2

2

Just drop the VALUES clause:

INSERT INTO Izdavanje (registracioniBrojKorisnika, imeKorisnika, identifikacioniBrojKnjige, vremeidatumIzdavanja) 
  SELECT @rbKorisnika, imeKorisnika, @idKnjige, GetDate()
  FROM Korisnici 
  WHERE registracioniBrojKorisnika=@rbKorisnika
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks! It's working! You cannot believe how much trouble I had with this piece of code! My brain sometimes suck so badly. Gracias!
Sorry, one more question. What is correct syntax if I wanna pull 2 values, not 1?
Just add the appropriate column name in the list.
0

May be, following query works perfectly for your issue. Just place proper datatype for @imeKorisnika variable.

DECLARE @imeKorisnika VARCHAR(50)
SELECT @imeKorisnika = imeKorisnika  FROM Korisnici  WHERE registracioniBrojKorisnika=@rbKorisnika

INSERT INTO Izdavanje (registracioniBrojKorisnika, imeKorisnika, identifikacioniBrojKnjige, vremeidatumIzdavanja) 
SELECT @rbKorisnika, @imeKorisnika, @idKnjige, GetDate() 

1 Comment

I actually had that idea and I tried that but I couldn't make it work, I probably messed up something in my attempt! Thanks! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.