Home All Groups Group Topic Archive Search About

How can I store the result to a variable in procedure?

Author
4 Nov 2005 2:36 AM
Kane
I have a problem when i write procedure on sqlserver 2000.
[code]
DECLARE @intTotalRecord int;
DECLARE @strTables varchar(200);
DECLARE @strWhereDescs varchar(200);
DECLARE @strSQL varchar(500);
SET @strTables = 'MyDB.dbo.MyTable';
SET @strWhereDescs = ' name like ''%kane%''';
SET @strSQL = 'SELECT COUNT(*) FROM ' + @strTables + ' WHERE ' +
@strWhereDescs + ' ';
execute(@strSQL);
[/code]
above works well.
than i need store the result to @intTotalRecord, how can i do?
i have try below:
[code]
....
SET @strSQL = 'SELECT @intTotalRecord=COUNT(*) FROM ' + @strTables + ' WHERE
' + @strWhereDescs + ' ';
....
[/code]
but that is a error:
"
msg 137,level 15,stat 1,line 1
'@intTotalRecord' must be declared.
"
But i have DECLARE @intTotalRecord.
Why?

Author
4 Nov 2005 3:00 AM
SQLChallenge
How about this??

DECLARE @intTotalRecord int
DECLARE @strTables varchar(200)
DECLARE @strWhereDescs varchar(200)
DECLARE @strSQL varchar(500)
DECLARE @strSQL2 nvarchar(500)
SET @strTables = 'information_schema.tables'
SET @strWhereDescs = ' table_name like ''%a%'''
SET @strSQL = 'SELECT COUNT(*) FROM ' + @strTables + ' WHERE ' +
@strWhereDescs + ' '
execute(@strSQL)
SET @strSQL2 = N'SELECT @intTotalRecord=COUNT(*) FROM ' + @strTables +
' WHERE ' + @strWhereDescs + ' '
EXECUTE sp_executesql @strSQL2,N'@intTotalRecord int
OUTPUT',@intTotalRecord OUTPUT
PRINT @intTotalRecord

---
Mark Graveline
Take The Challenge
http://www.sqlchallenge.com
---
Author
4 Nov 2005 3:13 AM
Kane
THX!  It works!
--
我是猪,哼哼


“SQLChallenge”编写:

Show quote
> How about this??
>
> DECLARE @intTotalRecord int
> DECLARE @strTables varchar(200)
> DECLARE @strWhereDescs varchar(200)
> DECLARE @strSQL varchar(500)
> DECLARE @strSQL2 nvarchar(500)
> SET @strTables = 'information_schema.tables'
> SET @strWhereDescs = ' table_name like ''%a%'''
> SET @strSQL = 'SELECT COUNT(*) FROM ' + @strTables + ' WHERE ' +
> @strWhereDescs + ' '
> execute(@strSQL)
> SET @strSQL2 = N'SELECT @intTotalRecord=COUNT(*) FROM ' + @strTables +
> ' WHERE ' + @strWhereDescs + ' '
> EXECUTE sp_executesql @strSQL2,N'@intTotalRecord int
> OUTPUT',@intTotalRecord OUTPUT
> PRINT @intTotalRecord
>
> ---
> Mark Graveline
> Take The Challenge
> http://www.sqlchallenge.com
> ---
>
>

AddThis Social Bookmark Button