How do I store the select column in a variable?

前端 未结 3 1455
你的背包
你的背包 2021-02-07 11:14

How do I store the select column in a variable?

I tried this, but it throws me an error "Incorrect syntax":

declare @EmpId int
SELECT  dbo.Employ         


        
3条回答
  •  心在旅途
    2021-02-07 11:52

    select @EmpID = ID from dbo.Employee
    

    Or

    set @EmpID =(select id from dbo.Employee)
    

    Note that the select query might return more than one value or rows. so you can write a select query that must return one row.

    If you would like to add more columns to one variable(MS SQL), there is an option to use table defined variable

    DECLARE @sampleTable TABLE(column1 type1)
    INSERT INTO @sampleTable
    SELECT columnsNumberEqualInsampleTable FROM .. WHERE ..
    

    As table type variable do not exist in Oracle and others, you would have to define it:

    DECLARE TYPE type_name IS TABLE OF (column_type | variable%TYPE | table.column%TYPE [NOT NULL] INDEX BY BINARY INTEGER;
    

    -- Then to declare a TABLE variable of this type: variable_name type_name;

    -- Assigning values to a TABLE variable: variable_name(n).field_name := 'some text';

    -- Where 'n' is the index value

提交回复
热议问题