SQL Server存儲過程中執行帶輸出參數的動態sql是很多人經常碰到的問題
CREATE procedure pUserList
(
@UserType char(
@pagenum int
@perpagesize int
@pagetotal int out
@rowcount int out
)
as
set nocount on
DECLARE @Err INT
declare @sql nvarchar(
declare @pagecount int
declare @sWhere nvarchar(
declare @sOrder nvarchar(
set @sWhere =
if not(@UserType is null)
set @sWhere = @sWhere +
set @sOrder =
declare @row_num int
LockTimeOutRetry:
create table #change (T_id int)
set @sql =
exec sp_executesql @sql
if @row_num % @perpagesize =
set @pagetotal = @row_num/@perpagesize
else
set @pagetotal = @row_num/@perpagesize +
set @rowcount = @row_num
if @row_num > @perpagesize
begin
set @row_num = @pagenum * @perpagesize
if @row_num = @perpagesize
begin
set @sql = N
+
exec sp_executesql @sql
SET @Err = @@ERROR
IF @Err <>
return
end
else
begin
set @row_num = (@pagenum
set @pagecount = @row_num
set @sql=N
+ cast(@pagecount as varchar) +
[User]
exec sp_executesql @sql
set @sql = N
exec sp_executesql @sql
SET @Err = @@ERROR
IF @Err <>
return
end
end
else
begin
set @sql =
from dbo
exec sp_executesql @sql
SET @Err = @@ERROR
IF @Err <>
return
end
ErrorHandler:
IF (@Err =
BEGIN
RAISERROR (
return
END
IF @Err =
BEGIN
WAITFOR DELAY
SET @ErrCounter = @ErrCounter +
GOTO LockTimeOutRetry
END
RAISERROR (@err
return
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
From:http://tw.wingwit.com/Article/program/SQL/201311/16271.html