一个简单的存储过程优化,谢谢!
create PROCEDURE [dbo].[bExistDir]
(@MySubject varchar(64),
@MyID int)
AS
BEGIN
declare @var1 nvarchar(128)
declare @iNum int;
select @var1 = 'select @a = count(*) from '+@MySubject + 'Dir' + ' where parentid = ' + rtrim(@MyID)
exec sp_executesql @var1,N'@a int output',@iNum output
if @iNum = 0
begin
return 0
end
else
begin
return 1
end
end
因为 if exist 效率应该比 count(*)高,所以想更改一下,但是不知道该如何写,谢谢!
------解决方案--------------------SQL code
if exists (select 1 from @MySubject where parentid = rtrim(@MyID))
return 1
else
return 0
------解决方案--------------------
SQL code
create PROCEDURE [dbo].[bExistDir]
(@MySubject varchar(64),
@MyID int)
AS
BEGIN
DECLARE @t TABLE(ID int)
INSERT @T EXEC('if exists(select 1 from '+@MySubject + 'Dir' + ' where parentid = ' + @MyID+') select 1 ')
IF EXISTS(SELECT 1 FROM @t)
return 1
ELSE
return 0
END