I am trying to create a select stored procedure where it takes a value from one table and sets this as a parameter for the second table.
As below I would like the user to input a reference number, which then gathers the registration ID from table 1, then performs a search in table two based on the registration ID, reference number and registration ID are both unique.
Reference number only exists in tableOne, registration_id exists in both
CREATE PROCEDURE SPSelect1
@Reference_Number NVARCHAR(10),
@Registration_ID NVARCHAR(10)
AS
SET @Registration_ID = (tblOne.registration_id WHERE reference_number = @Reference_Number)
SELECT *
FROM tblTwo
WHERE tblTwo.registration_id = @Registration_ID
END
The correct syntax is this:
SET @Registration_ID = (SELECT tblOne.registration_id where reference_number = @Reference_Number)
Or you could combine the two statements using a JOIN:
SELECT tblTwo.*
FROM tblTwo
JOIN tblOne ON tblTwo.registration_id = tblOne.registration_id
WHERE tblOne.reference_number = @Reference_Number
You could use:
select *
from tblTwo
where tblTwo.registration_id IN (SELECT tblOne.registration_id
FROM tblOne
WHERE reference_number = @Reference_Number)
i would like the user to input a reference number
Then your stored proc should only require a reference number as an input parameter. It can then query tblOne
to find the registration ID corresponding to that reference number, and then query tblTwo
using the registration ID in it's WHERE
clause.
reference number and registration ID are both unique
Since you specified that the two fields are unique, I would use an INNER JOIN
:
CREATE PROCEDURE SPSelect1
@Reference_Number NVARCHAR(10)
AS
BEGIN
SELECT *
FROM tblTwo
INNER JOIN tblOne
ON tblTwo.Registration_ID = tblOne.Registration_ID
WHERE tblOne.Reference_Number = @Reference_Number
END
GO
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.