0

I'd like to simultaneously do two things in an MSSQL query:

  1. select a field's value into a variable select @myvar = colName from tableName
  2. alias my column select colName as [myCol] from tableName

I've tried these things:

  • Attempted Syntax select @myvar = colName as [myCol] from tableName
  • Attempted Syntax select @myvar = (colName as [myCol]) from tableName
  • Attempted Syntax select (@myvar = colName) as [myCol] from tableName
  • checked select statement syntax: https://msdn.microsoft.com/en-us/library/ms176104.aspx

If this is possible, how can it be accomplished?

9
  • 1
    Why you need alias when assigning value to variable? Commented Feb 24, 2016 at 14:38
  • 3
    What impact would the alias have after the select? It would not be associated with @myvar and a select-assign returns no rows, do you want to assign and select as a row? - if so just select @myvar as [myCol] Commented Feb 24, 2016 at 14:38
  • @Faisal I don't strictly need the alias, but I desire it for maintenance reasons. Commented Feb 24, 2016 at 15:13
  • @AlexK. Impact: None on execution of the query. I don't want to select the variable value as a row, no. Thanks! Commented Feb 24, 2016 at 15:16
  • select @myvar = (select (select colName as [myCol] from tableName)) is probably the closes you will get if you want to do come kinf of textual analysis on the source Commented Feb 24, 2016 at 15:29

1 Answer 1

3

A select can either assign values to variables or return column values, but not both.

In some cases, e.g. when using select to provide data to an insert, an output clause may be useful. A tool well worth having in your pocket as it provides access to identity values from insert and both before and after values when used with update.

Sign up to request clarification or add additional context in comments.

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.