1

I have the following query in SQL Server

SELECT name,id FROM [someDatabase] 
where id like 'testName'

Now I want to use name and id in another query and define name as NAME and id as ID

SELECT DISTINCT vision FROM [someDatabase] WHERE name = NAME 

And id = ID

I'm not familiar with SQL server syntax. How do I define these two as local variables?

Thanks in advance.

2 Answers 2

1

You need to declare variables to hold the data first:

DECLARE @name VARCHAR(100),
        @id   INT

Then you can assign to these variables in your select statement. Note that this query will not produce any output.

SELECT @name = name,@id = id FROM [someDatabase] 
where id like 'testName'

Finally you can use these values in your query

SELECT DISTINCT vision FROM [someDatabase] WHERE name = @name 
And id = @id
Sign up to request clarification or add additional context in comments.

Comments

0
SELECT DISTINCT vision FROM [somedatabase] 
WHERE name IN (SELECT name FROM [someDatabase] where id like 'testName')
AND id IN (SELECT id FROM [someDatabase] WHERE id LIKE 'testName')

4 Comments

This does not answer the question
True but it should give the result he is after presupposing that the IDs are unique and LIKE 'testname' only produces one ID.
Why hit the same table 3 times when once will do it? Why bother using like with no wildcards?
Is it the same table? I thought he was querying the "vision" column from table_2 based on the id and name resulting from a query to a table_1, he doesn't exactly say. I was using LIKE because anders did in his question so I assume he needs the facility for a boolean variable here...?

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.