Monday, March 12, 2012

Place count in variable

Would like to know if this is even possible to do - using SQL Server 2000.
I am creating a procedure that truncates a table then inserts one row of dat
a.
In the third field I need to insert the count of another table.
I thought that this would work:
@.DetCount int = SELECT Count(*) FROM TableName
My question is can I assign a count(*) to a variable in a stored procedure?
I would then use the variable in the values clause of the insert statment.Hi Robert,
Yes - you can do that. You just need to wrap your Select Statement in
brackets.
e.g
Declare @.Count Int
Set @.Count = (Select count(*) From TableA)
Insert Into TableB (Col1)
Values (@.Count)
Select * From TableB
HTH
Barry|||Works perfect! Thanks a million.
"Barry" wrote:

> Hi Robert,
> Yes - you can do that. You just need to wrap your Select Statement in
> brackets.
> e.g
> Declare @.Count Int
> Set @.Count = (Select count(*) From TableA)
> Insert Into TableB (Col1)
> Values (@.Count)
>
> Select * From TableB
>
> HTH
> Barry
>|||The other option is to use the SELECT statement to assign values to a
variable:
SELECT @.Count = COUNT(*) FROM TableA
This is useful when setting the values of multiple variables at once,
e.g.:
SELECT @.Count = COUNT(*),
@.Avg = AVG(someColumn)
FROM TableA
HTH,
Stu

No comments:

Post a Comment