Select data directly into Variables in SQL Server

Here is an example of selecting data from a table with a query directly into a variable:

DECLARE @TaxRateMax smallmoney,
@TaxRateMin smallmoney,
@TaxRateAvg smallmoney;
SELECT @TaxRateMax = MAX (TaxRate),
@TaxRateMin = MIN (TaxRate),
@TaxRateAvg = AVG (TaxRate)
FROM Sales.SalesTaxRate;
SELECT @TaxRateMax AS TaxRateMax,
@TaxRateMin AS TaxRateMin,
@TaxRateAvg AS TaxRateAvg;

select_into_variable

To insert data into a table variable:

DECLARE @TempTaxRate TABLE (
StateProvinceID int,
TaxType tinyint,
TaxRate smallmoney,
Name nvarchar(50));
INSERT INTO
@TempTaxRate
SELECT
StateProvinceID,
TaxType,
TaxRate,
Name
FROM
Sales.SalesTaxRate
WHERE
TaxRate > 10;

SELECT * FROM @TempTaxRate

insert_into_table_variable

If the post helped you, please share it:
Pin It

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">