可以使用变量写出这个查询吗?

时间:2010-11-03 21:07:32

标签: sql sql-server

是否可以使用变量?

编写此查询

基本上我需要的是某些表中用于插入新记录的ID。现在我通过将该ID存储在变量中然后使用它来实现它。

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 个答案:

答案 0 :(得分:5)

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';

答案 1 :(得分:0)

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'

答案 2 :(得分:0)

使用子查询的另一种方法:

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')))