|
-
November 30th, 2003, 09:29 AM
#1
Sql query question
Hi everyone,
I am trying to do a select sub-query, but for some reason it is not working out.
I have the following stored procedure:
CREATE MyProcedure
@newID int,
@oldID int
AS
INSERT INTO MyTable(ExperimentID, Threshold, Energy) VALUES(@newID, Select Threshold, Energy from OldTable where ExperimentID = @oldID)
This mixing of a given value with a subquery does not seem to work. However, there must be a mechanism to do this. Does anyone has some experience with something like this and can maybe help me.
Thanks a lot.
Cheers,
Xargon
-
December 1st, 2003, 01:43 AM
#2
you can use a sub query only in the search clause or in the from clause. you cannot use it to substitute the values in an update or insert statement.
so what you will have to do is select the values into some local variables and then use them in your insert statement.
-
December 4th, 2003, 07:24 AM
#3
Well, according to MSDN, a select subquery is OK...
USE pubs
INSERT INTO MyBooks
SELECT title_id, title, type
FROM titles
WHERE type = 'mod_cook'
so, it should be possible.
maybe something like
Code:
INSERT INTO MyTable(ExperimentID, Threshold, Energy) VALUES(@newID, (Select Threshold, Energy from OldTable where ExperimentID = @oldID))
Hope I understood your question OK...
/* comment out enough code and your program will compile eventually */
-
December 4th, 2003, 08:51 AM
#4
CREATE MyProcedure
@newID int,
@oldID int
AS
INSERT INTO MyTable(ExperimentID, Threshold, Energy) VALUES(@newID, Select Threshold, Energy from OldTable where ExperimentID = @oldID)
The key is that the values clause does not handle a select subquery, however a noted you can replace the values cluase with a select query. With that in mind to do what you want you have to use the select logic as note INSERT .... SELECT ...
CREATE MyProcedure
@newID int,
@oldID int
AS
INSERT INTO MyTable (ExperimentID, Threshold, Energy) Select @newID, Threshold, Energy from OldTable where ExperimentID = @oldID
That follows the proper logic and will allow you to do what you are needing. Note however if ExperimentID is UNIQUE and the select may potentially return more than one value you have to add TOP 1 to the logic of the select or some other controller to make sure you get what you are after.
-
December 4th, 2003, 09:34 AM
#5
Thank you all
Cool guys :-)
Thank you all very much :-) This worked :-)
Pankaj
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|