0

Is there a way for me to save the values my SELECT statement returns in to a variable in SQL?

This is what i want to do, first i want to SELECT all the columns i wanna check so in this case ItemNames of the items with ItemCategory US.

SELECT `ItemName` where `ItemCategory´= 'US'

Then I want to save the ItemName from the statement above into a variable in SQL to use it later on in the same query. Like this:

SELECT `DatabaseID` where `Project` NOT LIKE `myVariable`

Thanks in regards

2

3 Answers 3

7

You can try like this:

SELECT `ItemName` into @myVar FROM mytable where `ItemCategory´= 'US';

or

SELECT @myVar := `ItemName` FROM mytable where `ItemCategory´= 'US'

However you can combine your query to one like this:

SELECT `DatabaseID` from mytable 
where `Project` NOT IN (SELECT `ItemName` where `ItemCategory´= 'US')
Sign up to request clarification or add additional context in comments.

Comments

1
declare @var varchar(50);
SELECT @var = 'US' 
SELECT * FROM Country where Name NOT LIKE @var

Comments

0

What you can do is store the results in a variable table or temporary table, something like this:

SQL Server:

create table #Temp
(
    ItemName As Varchar(50)
    --col2 AS Int, 
    --col3 As Varchar(20)
    --...
)

MySQL

CREATE TEMPORARY TABLE IF NOT EXISTS table1 (ItemName VARCHAR(50)) -- You can add more columns: (ItemName VARCHAR(50), col2 int NOT NULL DEFAULT 0, col3 VARCHAR(20),...)

Then put the results in the table #Temp or table1

SQL Server

Insert Into #Temp SELECT ItemName FROM mytable where ItemCategory= 'US';

MySQL

Insert Into table1 SELECT ItemName FROM mytable where ItemCategory= 'US';

And then you can play with both tables and make different operations (e.g. make joins)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.