(SQL) What's wrong with my syntax?

Status
Not open for further replies.

Keef

Ars Tribunus Militum
2,094
Code:
ALTER TABLE Foo
ADD CONSTRAINT fk_bar FOREIGN KEY 
bar(nvarchar(255), null)
REFERENCES herp.derp(foobar);

Nets me a
Code:
Msg 102, Level 15, State 1, Line 3
Incorrect syntax near 'bar'.
message.

I've tried multiple variations of the command but I keep getting a similar error message. This is on SQL Server 2008. Its a test db so I'm not too concerned about messing up.
 

TheDan666

Ars Tribunus Militum
2,359
Keef":30cc1t2j said:
On the 3rd line: nvarchar(255).
In essence, I'm trying to create a new column and making it a foreign key. Am I going about that the wrong way? Do I need to copy over that column from the other table?

Yes. You have to create the column first before you can define a constraint on it (at least via alter table). You want something like this:

ALTER TABLE Foo
add bar(nvarchar(255), null);

ALTER TABLE Foo
add CONSTRAINT fk_bar
FOREIGN KEY (bar)
REFERENCES herp.derp(foobar);
 

Keef

Ars Tribunus Militum
2,094
Ugh,

So I get this now:

Code:
There are no primary or candidate keys in the referenced table 'RDTScreen.dbo.NotesSet' that match the referencing column list in the foreign key 'FK_Notepad'.

Solution from what I understand from explanations is that I have to create corresponding columns for all the foreign keys on that table even though I just want to use the one, is that right?
 
Status
Not open for further replies.