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 |
ann
Posting Yak Master
220 Posts |
Posted - 2006-08-01 : 11:01:51
|
What I need to do:1. If exists in table 1, then retrieve the ID from table 12. Insert new record with table1 ID into table 23. if doesn't exist in table 1, then just insert new record into table 2What I have so far:If EXISTS (SELECT CaseID FROM Cases WHERE ccNumber=@ccNumber ) Insert INTO Compromised ( CaseID, ccNumber,...) Values (*caseID, @ccNumber,...) ELSEINSERT INTO Compromised ( ccNumber,.... )VALUES ( @ccNumber, ... )Where I'm stuck:I don't know how to get the CaseID when it exists, so I can insert itinto the new table. Can anyone help me? Thanks |
|
nr
SQLTeam MVY
12543 Posts |
Posted - 2006-08-01 : 11:15:19
|
insert Compromised ( CaseID, ccNumber,...)select CaseID, ccNumber, ...from Cases where ccNumber=@ccNumberif @@rowcount = 0insert Compromised (ccNumber,...)select @ccNumber, ...==========================================Cursors are useful if you don't know sql.DTS can be used in a similar way.Beer is not cold and it isn't fizzy. |
 |
|
ann
Posting Yak Master
220 Posts |
Posted - 2006-08-03 : 14:34:58
|
I tried the example you provided but I get the following error:The name 'caseID' is not permitted in this context. Only constants, expressions, or variables allowed here. Column names are not permitted. |
 |
|
Srinika
Master Smack Fu Yak Hacker
1378 Posts |
Posted - 2006-08-03 : 15:13:09
|
ann,r u using the exactly same code or using the "Values" keyword and brackets ?Srinika |
 |
|
ann
Posting Yak Master
220 Posts |
Posted - 2006-08-03 : 15:23:12
|
I'm using Values, brackets and INTO |
 |
|
Srinika
Master Smack Fu Yak Hacker
1378 Posts |
Posted - 2006-08-03 : 16:48:48
|
ann,That is the reasonthe code given by nr doesn't have "Values" keywordcheck the syntax for "Insert" in Books OnLine.Quick Info.Use values when u have fixed values as constants. if u get data from a select query, and insert, u can't use "Values" keyword.Syntax isInsert Into DestinationTbl (<Fields list>)Select <Fields & constants> from SourceTblValues used as follows :Insert Into DestinationTbl (Field1, Field2....)Values (Data1, Data2,....)Srinika |
 |
|
ann
Posting Yak Master
220 Posts |
Posted - 2006-08-03 : 17:06:16
|
I didn't know that - will that query also allow me to pass in parameters? I am using that query in a stored procedure. What I came up with is something like this which works (I didn't know how else to do it):DECLARE @var1 intSELECT @var1 = CaseIDFROM CaseWHERE ccNumber=@ccNUMif @@rowcount > 0INSERT INTO Compromised .....else..... |
 |
|
|
|
|
|
|