1、使用Sp_executeSql执行SQL,用输出参数获得其变量
declare @val varchar(100)
declare @Sql nvarchar(4000)
set @Sql = 'Set @val=5'
exec Sp_executeSql @Sql, N'@val varchar(100) output',@val output
select @val as Value
declare @Sql nvarchar(4000)
set @Sql = 'Set @val=5'
exec Sp_executeSql @Sql, N'@val varchar(100) output',@val output
select @val as Value
其中@Sql字符串,必须为 ntext/nchar/nvarchar三种类型中的一种,否则会出错
(以下摘自CSDN)
2、在存储过程中使用RaisError,传回错误讯息
IF @@Error<>0
RaisError '更新数据时错误',16,1
return
如果执行间段错误,傳回使用者自訂的錯誤訊息,並設定系統旗標,記錄曾發生過錯誤。
VB6用戶端获取错误信息:
On Error GoTo ErrDo
.......
ErrDo:
MsgBox "保存數據出錯: " & Err.Description
代码
IF OBJECT_ID ( 'Production.usp_GetList', 'P' ) IS NOT NULL
DROP PROCEDURE Production.usp_GetList;
GO
CREATE PROCEDURE Production.usp_GetList @product varchar(40)
, @maxprice money
, @compareprice money OUTPUT
, @listprice money OUT
AS
SELECT p.name AS Product, p.ListPrice AS 'List Price'
FROM Production.Product p
JOIN Production.ProductSubcategory s
ON p.ProductSubcategoryID = s.ProductSubcategoryID
WHERE s.name LIKE @product AND p.ListPrice < @maxprice;
-- Populate the output variable @listprice.
SET @listprice = (SELECT MAX(p.ListPrice)
FROM Production.Product p
JOIN Production.ProductSubcategory s
ON p.ProductSubcategoryID = s.ProductSubcategoryID
WHERE s.name LIKE @product AND p.ListPrice < @maxprice);
-- Populate the output variable @compareprice.
SET @compareprice = @maxprice;
GO
DROP PROCEDURE Production.usp_GetList;
GO
CREATE PROCEDURE Production.usp_GetList @product varchar(40)
, @maxprice money
, @compareprice money OUTPUT
, @listprice money OUT
AS
SELECT p.name AS Product, p.ListPrice AS 'List Price'
FROM Production.Product p
JOIN Production.ProductSubcategory s
ON p.ProductSubcategoryID = s.ProductSubcategoryID
WHERE s.name LIKE @product AND p.ListPrice < @maxprice;
-- Populate the output variable @listprice.
SET @listprice = (SELECT MAX(p.ListPrice)
FROM Production.Product p
JOIN Production.ProductSubcategory s
ON p.ProductSubcategoryID = s.ProductSubcategoryID
WHERE s.name LIKE @product AND p.ListPrice < @maxprice);
-- Populate the output variable @compareprice.
SET @compareprice = @maxprice;
GO
另一个存储过程调用的时候:
DECLARE @compareprice money, @cost money
EXECUTE Production.usp_GetList '%Bikes%', 700,
@compareprice OUT,
@cost OUTPUT
SELECT @compareprice,@cost
4、创建一个临时表
#tempTable (userName nvarchar(50))
insert into #tempTable(userName)
exec GetUserName
select #tempTable
--用完之后要把临时表清空
drop table #tempTable