|
database
newsgroups
|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
Set mult vars via one select?Its looking like this isn't possible - but is there a way to set multiple
variables to specific values returned from a single select? ie Declare @A as VarChar(50) Declare @B as VarChar(50) Declare @C as VarChar(50) Set @A, @B, @C = (SELECT ColA, ColB, ColC FROM TblName Where PriKey = 500) OR, would I need to have separate SELECTs per variable? Set @A = (Select ColA from TblName Where PriKey = 500) Set @B = (Select ColB from TblName Where PriKey = 500) Set @C = (Select ColC from TblName Where PriKey = 500) OR, is there a better way entirely? Just to expand a bit on Stu's answer:
If SQL Server allowed "row valued constructors" (in ANSI SQL), you could do: Set (@A, @B, @C) = (SELECT ColA, ColB, ColC FROM TblName Where PriKey = 500) Just as you can do today, both with only one column. If the SELECT return 0 rows, the variables would have NULL If the SELECT returns > 1 rows, you get an error. The SQL Server way (which Stu posted) work differently: If the SELECT return 0 rows, the variables are untouched If the SELECT returns > 1 rows, a assignment will be done, but you cannot control from which of the rows returned. As you can see, without knowledge of this, you can get pretty creepy bugs in your code (if several rows are returned). Make sure you check @@ROCOUNT if you cannot be 100% that there are only 1 rows returned and the initial variable value is NULL. -- Show quoteTibor Karaszi, SQL Server MVP http://www.karaszi.com/sqlserver/default.asp http://www.solidqualitylearning.com/ Blog: http://solidqualitylearning.com/blogs/tibor/ "mikeb" <m***@nohostanywhere.com> wrote in message news:ergmMXtnFHA.1412@TK2MSFTNGP09.phx.gbl... > Its looking like this isn't possible - but is there a way to set multiple variables to specific > values returned from a single select? > > ie > Declare @A as VarChar(50) > Declare @B as VarChar(50) > Declare @C as VarChar(50) > > Set @A, @B, @C = (SELECT ColA, ColB, ColC FROM TblName Where PriKey = 500) > > OR, would I need to have separate SELECTs per variable? > > Set @A = (Select ColA from TblName Where PriKey = 500) > Set @B = (Select ColB from TblName Where PriKey = 500) > Set @C = (Select ColC from TblName Where PriKey = 500) > > OR, is there a better way entirely? > > > |
|||||||||||||||||||||||