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.
| Author |
Topic |
|
overbored
Starting Member
12 Posts |
Posted - 2002-01-17 : 18:15:05
|
| I log visitors in a database that has two tables: Hits and IPs (this is just a simplification). Hits has three columns: hit_id (identity int), hit_time (datetime), and ip_id (int). The last one is related to the IPs table, which has columns: ip_id and ip_address (varchar(16)).Currently, I use this stored procedure for logging to simplify things on the ASP side:>>>CREATE PROCEDURE insert_hit(@ip_address varchar(16))ASDECLARE@cur CURSOR,@ip_id int-- Get the IP IDSET @cur = CURSOR SCROLL DYNAMIC FORSELECT ip_id FROM IPsWHERE ip_address = @ip_addressOPEN @curFETCH FIRST FROM @cur INTO @ip_idIF @@FETCH_STATUS = -1BEGININSERT INTO IPs (ip_address) VALUES (@ip_address)FETCH FIRST FROM @cur INTO @ip_idENDCLOSE @cur-- Insert row into HitsINSERT INTO Hits (ip_id, hit_time) VALUES (@ip_id, GETDATE())>>>Now, I'm not having any problems with this script, but as you can see, it's extremely tedious - especially with the various other related data being logged. Moreover, this doesn't seem to me like an unusual case; I figured this is a major aspect of the "R" in "RDBMSs."My question is: Is there a way to perform a "smart" INSERT statement? That is, one which will automatically insert passed data into a separate table if it isn't there, then use the respective ID from that entry as the value for the related field in the main table? |
|
|
byrmol
Shed Building SQL Farmer
1591 Posts |
Posted - 2002-01-17 : 18:29:51
|
Overboard,It seems that you are only using the cursor for an existence check..Try ThisCREATE PROCEDURE insert_hit(@ip_address varchar(16))ASset nocount ondeclare @IP_ID int--Check for a recordIF NOT EXISTS (Select 1 from Ips where ip_address = @ip_address)BEGIN --Doesn't exists so add it INSERT INTO IPs (ip_address) VALUES (@ip_address)END--Retrieve IDSelect @IP_ID = IP_ID from Ips where ip_address = @ip_address--Insert into HitsINSERT INTO Hits (ip_id, hit_time) VALUES (@ip_id, GETDATE())go HTHDavidMTomorrow is the same day as Today was the day before. |
 |
|
|
overbored
Starting Member
12 Posts |
Posted - 2002-01-17 : 21:39:39
|
| Thanks!!! That's a helluvalot better. |
 |
|
|
|
|
|
|
|