Insert Into a table a variable outside of the SELECT results

时间:2016-07-11 20:23:28

标签: sql sql-server tsql stored-procedures

I am working on a Stored Procedure on MSSQL. This is a simplified example of my case.

another code that has declared a variable @Country
...
...
...
INSERT INTO Customers (CustomerName, Country)
SELECT SupplierName, Country FROM Suppliers;

So, what I try to do is instead of the Country value of the SELECT, insert the @Country variable of the previous code, but keep the SupplierName from the results.

I wasn't able to find a similar question and trial and error didn't help.

2 个答案:

答案 0 :(得分:3)

Just use the variable instead:

Insert Into Customers (CustomerName, Country)
Select SupplierName, @Country 
From Suppliers;

答案 1 :(得分:1)

Well someone beat me to the punch (@Siyual), but just use the variable in the select (example of this below)

CREATE TABLE #temp1 (
    id INT,
    value INT
    )

CREATE TABLE #temp2 (
    id INT,
    value INT
    )

DECLARE @newVal INT

SET @newVal = 10

INSERT INTO #temp1 (
    id,
    value
    )
VALUES (
    1,
    1
    )

INSERT INTO #temp1 (
    id,
    value
    )
VALUES (
    2,
    2
    )

INSERT INTO #temp1 (
    id,
    value
    )
VALUES (
    3,
    3
    )

INSERT INTO #temp2 (
    id,
    value
    )
SELECT id,
    @newVal
FROM #temp1

SELECT *
FROM #temp2