标签:
ALTER PROCEDURE [dbo].[feili]
(@OBJECTID nvarchar(100))
AS
DECLARE @sql1 nvarchar(MAX);
BEGIN
SET @sql1=‘SELECT * FROM FEILIPOINT where OBJECTID=‘+@OBJECTID
EXEC sp_executesql @sql1;
END
上面是在外部给变量赋值,也可以在内部直接给变量设置默认值
ALTER PROCEDURE [dbo].[feili] (@OBJECTID nvarchar(100)=‘1‘) AS BEGIN SELECT * FROM FEILIPOINT where OBJECTID=@OBJECTID EXEC feili; END
也可以把变量的内容输出,使用output
ALTER PROCEDURE [dbo].[feili] ( @OBJECTID nvarchar(100) ) AS DECLARE @sql1 nvarchar(MAX); DECLARE @num INT; BEGIN SET @sql1=‘SELECT @num=count(*) FROM FEILIPOINT where OBJECTID=‘+@OBJECTID EXEC sp_executesql @sql1,N‘@num int output‘,@num OUTPUT; SELECT @num; END
以上是全局变量,下面来了解局部变量
局部变量也称为内部变量。局部变量是在函数内作定义说明的。其作用域仅限于函数内部,离开该函数后再使用这种变量是非法的。
局部变量的定义:必须先用Declare命令定以后才可以使用,declare{@变量名 数据类型}
局部变量的赋值方法:set{@变量名=表达式}或者select{@变量名=表达式}
局部变量的显示:select @变量名
ALTER PROCEDURE [dbo].[feili] AS DECLARE @objectid nvarchar(100); BEGIN DECLARE @sql1 nvarchar(MAX); SET @objectid=‘10‘; SET @sql1=‘SELECT * FROM FEILIPOINT WHERE objectid=‘+@objectid; EXEC sp_executesql @sql1; END
也可以这样写
ALTER PROCEDURE [dbo].[feili] AS DECLARE @objectid nvarchar(100);//该变量若需要动态使用,还需要在exec中进行声明 BEGIN DECLARE @sql1 nvarchar(MAX); SET @objectid=‘10‘; SET @sql1=‘SELECT * FROM FEILIPOINT WHERE objectid=@objectid‘; EXEC sp_executesql @sql1,N‘@objectid nvarchar(max)‘,@objectid; END
标签:
原文地址:http://www.cnblogs.com/ggz19/p/5097372.html