• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 363
  • Last Modified:

Fill multiple variables with only one select

Hello dear experts,

I am wondering if it is possible to fill multiple variables at the same time in T-SQL.

i.e:
SELECT @FBText = (SELECT ProjectFeedbackText FROM Project_Feedback WHERE FeedbackId = @FBId)
SELECT @FBDate = (SELECT PostDate FROM Project_Feedback WHERE FeedbackId = @FBId)
SELECT @FBSenderId = (SELECT UserId FROM Project_Feedback WHERE FeedbackId = @FBId)

Is it possible to fill the 3 variables with only one select, without using a cursor ?
Thanks
0
EPCOS
Asked:
EPCOS
1 Solution
 
chapmandewCommented:
sure:

SELECT @FBText =ProjectFeedbackText, @FBDate = PostDate, @FBSenderId = UserId
 FROM Project_Feedback WHERE FeedbackId = @FBId
0
 
reb73Commented:
Yes -

SELECT  TOP 1
             @FBText = ProjectFeedbackText
            ,@FBDate = PostDate
            ,@FBSenderId = UserId
FROM
         Project_Feedback WHERE FeedbackId = @FBId


(Using Top 1 is to ensure there are not multiple values being returned which can cause an error)
0
 
chapmandewCommented:
if FeedbackId is unique,no reason to use TOP 1
0
 
EPCOSAuthor Commented:
Thank you :)
0
 
BrandonGalderisiCommented:
Also, more than one record being returned will NOT result in an error with reb's example.  It will just only return one set of values, not all.

SELECT  TOP 1
             @FBText = ProjectFeedbackText
            ,@FBDate = PostDate
            ,@FBSenderId = UserId
FROM
         Project_Feedback WHERE FeedbackId = @FBId



If more than one record could be returned for a single feedbackID, then this would result in an error:

SELECT @FBText = (SELECT ProjectFeedbackText FROM Project_Feedback WHERE FeedbackId = @FBId)
SELECT @FBDate = (SELECT PostDate FROM Project_Feedback WHERE FeedbackId = @FBId)
SELECT @FBSenderId = (SELECT UserId FROM Project_Feedback WHERE FeedbackId = @FBId)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now