Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 Categories Table. How to implement this?

Author  Topic 

shapper
Constraint Violating Yak Guru

450 Posts

Posted - 2007-02-05 : 18:21:54
Hello,

I have a documents table with the following fields:

[DocumentId] (PK)
[DocumentTitle]
[DocumentUrl]
[DocumentCategoryId] (FK)

And a categories table with the following fields:

[CategoryId] (PK)
[CategoryName]

I want to create a new document on documents table and provide a category name. Then I want to retrieve the CategoryId for given CategoryName and place it in DocumentCategoryId.

How can I do this?

And is this the way to do this?

Thanks,
Miguel

khtan
In (Som, Ni, Yak)

17689 Posts

Posted - 2007-02-05 : 18:31:02
step 1 : insert record into the categries table
step 2 : insert record into the documents table


KH

Go to Top of Page

Michael Valentine Jones
Yak DBA Kernel (pronounced Colonel)

7020 Posts

Posted - 2007-02-05 : 19:30:37
[code]
insert into documents
(
[DocumentTitle],
[DocumentUrl],
[DocumentCategoryId]
)
select
[DocumentTitle] = @DocumentTitle,
[DocumentUrl] = @DocumentUrl,
[DocumentCategoryId] =
(
Select
a.[CategoryId]
from
categories a
where
a.[CategoryName] = @CategoryName
)
[/code]

CODO ERGO SUM
Go to Top of Page

shapper
Constraint Violating Yak Guru

450 Posts

Posted - 2007-02-06 : 08:44:15
Hi Michael,

Thank you for our help.
I am trying your code and I am having just 2 questions:
1. Why the use of []? I usually don't use them.
2. What is the meaning of using 'a'? Is like a temporary entity in SQL?

Most of the time I work with .NET code so somethings in SQL still are confusing to me.

Thanks,
Miguel
Go to Top of Page

shapper
Constraint Violating Yak Guru

450 Posts

Posted - 2007-02-06 : 08:46:36
Just an update to my last post:

Usually I use something like this:

INSERT Documents (DocumentTitle, DocumentUrl)
VALUES (@DocumentTitle, @DocumentUrl)

This is the structure which I am familiar with.
So I don't use [], I don't have INTO ...

I am not sure if I am doing something wrong

Thanks,
Miguel
Go to Top of Page

DonAtWork
Master Smack Fu Yak Hacker

2167 Posts

Posted - 2007-02-06 : 08:47:56
2. a is used as the Table Alias.

[Signature]For fast help, follow this link:
http://weblogs.sqlteam.com/brettk/archive/2005/05/25.aspx
Learn SQL
http://www.sql-tutorial.net/
http://www.firstsql.com/tutor.htm
http://www.w3schools.com/sql/default.asp
Go to Top of Page
   

- Advertisement -