日期:2014-05-18  浏览次数:20440 次

求一个通过现有表中的条件去匹配其他表中记录的存储过程
Id content guid
1 (status = '新增') and (sid = '1') test1
2 (status = '新增') test1
3 (status = '批准') test1
4 (status = '新增') and (sid = '2') test2
5 (status = '未批准') Test2
…… …… ……

现在有上面一个表,content字段里放的是一组条件,要求写一个存储过程,
参数有4个,tablename,gid,id_value,test,输出上表中的id。
通过tablename表名,gid关键字,value关键字的值就可以确定唯一一条记录,test是上面表里guid的其中以个值,如test1,test2……
通过test所对应的一些content,找出和上面的那个唯一记录中最匹配的一个content的id,并通过该存储过程输出这个id,如果一条记录匹配多个content,则选择匹配content的最多的那个id。
注:表中的记录有status,sid等content字段中出现的字段。


------解决方案--------------------
没看明白,等老大
------解决方案--------------------
我看你表达的意思,我觉得用表关联查询应该可以解决问题


------解决方案--------------------
SQL code
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