MSSQL how to get value from table into variable ?

hi .. let's say i have a table and a variable.

SELECT email from parent where username = @pusername;  

will return the value that i need to have in @mail variable..

how can i set the @mail variable to get the value of the above sql query ? i also know that it will return only one result .
thanks in advance
cookingAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
RiteshShahConnect With a Mentor Commented:
sorry I did typo in WHERE clause in above example, it should be like below snippet, even check your table and field name before you run.


declare @mail varchar(50)

select @mail=email from parent where username = @pusername;

select @mail
0
 
RiteshShahCommented:
declare @mail varchar(50)

select @mail=email from parent where username=@parentname

select @mail
0
 
RiteshShahCommented:
you are sure about that your query will return only one value so there is no problem at all, since there is no concept like array in SQL Server so if your query will return more than one row in above query, only last email address will be stored in @mail variable.
0
 
bull_riderConnect With a Mentor Commented:
You can do this in two ways. One which RiteshShah has suggested and the other way is to use the Set option to store a value into a variable.

Declare @mail nvarchar(255)

Set @mail = (SELECT email from parent where username = @pusername)

Select @mail

You can use anyone of them accotding to your convenience.
0
 
RiteshShahCommented:
generally in the situation Author has, I would go for SELECT not for SET, nothing much different but just wanted to stick with ANSI standard, basically SET is used to assign static value and SELECT is for getting value in variable from QUERY. have a look.

http://www.sqlhub.com/2009/03/set-and-select-in-sql-server-2005.html
0
All Courses

From novice to tech pro — start learning today.