Can this query be written using a variable?

Is it possible to write this query using a variable?

Basically, I need the identifier of some thing from some table to insert a new record. Now I am doing this by storing this identifier in a variable and then using it.

DECLARE @store_num char(4);
SELECT  @store_num = [store_no] FROM store WHERE (store_name = 'Rocky Mountain Produce');
INSERT INTO [ITD640_B].[dbo].[employee]
           ([employee_no]
           ,[employee_fname]
           ,[employee_lname]
           ,[store_no])
     VALUES
           (123456
           ,'YourFirstName'
           ,'YourLastName'
           ,@store_num);
+3
source share
3 answers
INSERT INTO [ITD640_B].[dbo].[employee]
     ([employee_no]
     ,[employee_fname]
     ,[employee_lname]
     ,[store_no])
SELECT 
     123456
     ,'YourFirstName'
     ,'YourLastName'
     ,[store_no]
FROM 
     store 
WHERE 
     store_name = 'Rocky Mountain Produce';
+5
source
INSERT INTO [ITD640_B].[dbo].[employee]
           ([employee_no]
           ,[employee_fname]
           ,[employee_lname]
           ,[store_no])
     SELECT
           123456
           ,'YourFirstName'
           ,'YourLastName'
           ,[store_no]
        FROM store
        WHERE store_name = 'Rocky Mountain Produce'
0
source

Another method using a subquery:

INSERT INTO [ITD640_B].[dbo].[employee]
           ([employee_no]
           ,[employee_fname]
           ,[employee_lname]
           ,[store_no])
     VALUES
           (123456
           ,'YourFirstName'
           ,'YourLastName'
           ,(SELECT [store_no] FROM store WHERE (store_name = 'Rocky Mountain Produce')))
0
source

Source: https://habr.com/ru/post/1772941/


All Articles