SQL Server - 将SELECT语句存储到存储过程中的变量中

时间:2021-03-30 10:08:12

In my Stored Procedure, I am trying to store the result of a SELECT statement inside a variable. This is what I have so far:

在我的存储过程中,我试图将SELECT语句的结果存储在变量中。这是我到目前为止:

DECLARE @process_pk uniqueidentifier
INSERT INTO @process_pk
    SELECT process_pk 
    FROM dbo.Process 
    WHERE process_id = @process_id

In the above, I'm trying to store the result of the SELECT statement into my variable @process_pk, to be used sometime later in the latter part of my stored procedure. But it doesn't seem to be the correct syntax.

在上面,我试图将SELECT语句的结果存储到我的变量@process_pk中,以便稍后在我的存储过程的后半部分使用。但它似乎不是正确的语法。

I would like to ask what is the correct way to store SELECT statement results inside a Stored Procedure variable so that it can be used anytime within the stored procedure.

我想问一下在存储过程变量中存储SELECT语句结果的正确方法是什么,以便可以在存储过程中随时使用它。

2 个解决方案

#1


2  

You should use SET

你应该使用SET

SET @process_PK = (SELECT process_pk 
    FROM dbo.Process 
    WHERE process_id = @process_id)

#2


1  

You can set the value in the SELECT:

您可以在SELECT中设置值:

SELECT @process_pk = process_pk 
FROM dbo.Process 
WHERE process_id = @process_id;

This is particularly handy if you want to set multiple values from the same query:

如果要从同一查询中设置多个值,这尤其方便:

SELECT @process_pk = p.process_pk,
       @col1 = p.col1 
FROM dbo.Process p 
WHERE p.process_id = @process_id;

#1


2  

You should use SET

你应该使用SET

SET @process_PK = (SELECT process_pk 
    FROM dbo.Process 
    WHERE process_id = @process_id)

#2


1  

You can set the value in the SELECT:

您可以在SELECT中设置值:

SELECT @process_pk = process_pk 
FROM dbo.Process 
WHERE process_id = @process_id;

This is particularly handy if you want to set multiple values from the same query:

如果要从同一查询中设置多个值,这尤其方便:

SELECT @process_pk = p.process_pk,
       @col1 = p.col1 
FROM dbo.Process p 
WHERE p.process_id = @process_id;