日期:2014-05-18 浏览次数:20455 次
IF object_id('tc') IS NOT NULL
DROP TABLE tc
GO
CREATE TABLE tc
(
id INT,
cont VARCHAR(100),
guid VARCHAR(20)
)
GO
INSERT tc SELECT 1, '(status = ''新增'')', 'test1'
UNION ALL SELECT 2, '(status = ''新增'') and (sid = ''1'')' ,'test1'
UNION ALL SELECT 3, '(status = ''批准'')' ,'test1'
UNION ALL SELECT 4, '(status = ''新增'') and (sid = ''2'')', 'test2'
UNION ALL SELECT 5, '(status = ''未批准'')' ,'test2'
GO
IF object_id('list') IS NOT NULL
DROP TABLE list
GO
CREATE TABLE list
(
gid INT,
status VARCHAR(20),
sid INT
)
GO
SET NOCOUNT ON
INSERT INTO list SELECT 1,'新增', 1
INSERT INTO list SELECT 2,'批准' ,2
INSERT INTO list SELECT 3,'新增' ,2
INSERT INTO list SELECT 4,'批准',1
INSERT INTO list SELECT 5,'未批准', 1
SET NOCOUNT OFF
GO
SELECT * FROM tc
GO
SELECT * FROM list
GO
IF OBJECT_ID('p_test','p') IS NOT NULL
DROP PROC p_test
GO
CREATE PROC p_test
(
@tb VARCHAR(50),
@key VARCHAR(50),
@value VARCHAR(50),
@test VARCHAR(20),
@out_condition_id INT OUTPUT
)
AS
BEGIN
IF object_id('#t_tmp') IS NOT NULL
DROP TABLE #t_tmp
DECLARE
@ext BIT,
@nid INT,
@cnt INT,
@id VARCHAR(50),
@cont VARCHAR(2000)
SELECT
@ext = 0,
@nid = 1
SELECT nid=IDENTITY(INT),id*1 id,cont
INTO #t_tmp
FROM tc
WHERE guid = @test
DECLARE @t TABLE
(
nid INT,
cnt INT
)
SELECT @cnt = @@ROWCOUNT
DECLARE @ccnt INT
WHILE @nid <=@cnt
BEGIN
DECLARE @sql NVARCHAR(2000)
SELECT @cont = cont FROM #t_tmp WHERE nid = @nid
SET @sql = N'SELECT @id=RTRIM(' + @key + ') FROM ' + @tb + ' WHERE ' + @cont + ' AND ' + @key + '=''' + @value + ''''
EXEC sp_executeSQL @sql,N'@id VARCHAR(50) OUTPUT',@id OUTPUT
IF @id IS NULL OR @id != @value
SELECT @nid = @nid + 1,@id=NULL
ELSE
BEGIN
SET @sql=N'SELECT @ccnt = COUNT(*) FROM ' + @tb + ' WHERE ' + @cont
EXEC sp_executeSQL @sql,N'@ccnt INT OUTPUT',@ccnt OUTPUT
INSERT @t SELECT id,@ccnt FROM #t_tmp WHERE nid=@nid
SET @nid=@nid+1
END
END
SELECT TOP 1