Ask Your Question
4

How can the output of an SQL query be assigned to a variable in TSQL?

asked 2021-08-14 11:00:00 +0000

lakamha gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-11-29 00:00:00 +0000

qstack gravatar image

To assign the output of an SQL query to a variable in T-SQL, you can use the SELECT INTO syntax as follows:

DECLARE @myVariable varchar(50)
SELECT @myVariable = columnName FROM myTable WHERE someCondition

-- OR

SELECT @myVariable = (SELECT columnName FROM myTable WHERE someCondition)

In the above syntax, replace @myVariable with the name of the variable you want to assign the output to, columnName with the name of the column whose value you want to assign, myTable with the name of the table that contains the column, and someCondition with the condition that specifies which row to select.

You can also use the SET syntax as shown below:

DECLARE @myVariable varchar(50)
SET @myVariable = (SELECT columnName FROM myTable WHERE someCondition)

Both of these methods will assign the value of the selected column to the variable, allowing you to use it in subsequent queries or calculations.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-08-14 11:00:00 +0000

Seen: 9 times

Last updated: Nov 29 '21