--结果:
id des
1 偶然间水立方<a href="#">我a>是划分的框架<a href="#">你a>的
2 苏利文哦<a href="#">她a>上电缆附件<a href="#">你a>塑料袋解放<a href="#">他a>
3 姿势踢球<a href="#">他a>
说明
1、就是t2表中的des字段内容,如果在t1表的name字段有对应,则替换成链接
2、如果是再次替换,则已经替换的不再替换
3、t2表名可作参数传入,因为可能有多表,但是结构一样
--游标法(在原表更新数据):
--------------------------------------------------------------------------
-- Author : htl258(Tony)
-- Date : 2010-04-19 18:25:33
-- Version:Microsoft SQL Server 2008 (RTM) - 10.0.1600.22 (Intel X86)
-- Jul 9 2008 14:43:34
-- Copyright (c) 1988-2008 Microsoft Corporation
-- Developer Edition on Windows NT 5.1
--------------------------------------------------------------------------
--> 生成测试数据表:t1
IF NOT OBJECT_ID('[t1]') IS NULL
DROP TABLE [t1]
GO
CREATE TABLE [t1]([id] INT,[name] NVARCHAR(10))
INSERT [t1]
SELECT 1,N'我' UNION ALL
SELECT 2,N'你' UNION ALL
SELECT 3,N'他' UNION ALL
SELECT 4,N'她'
GO
--SELECT * FROM [t1]
--> 生成测试数据表:t2
IF NOT OBJECT_ID('[t2]') IS NULL
DROP TABLE [t2]
GO
CREATE TABLE [t2]([id] INT,[des] NVARCHAR(1000))
INSERT [t2]
SELECT 1,N'偶然间水立方我是你的' UNION ALL
SELECT 2,N'苏利文哦她上电缆附件你塑料袋解放他' UNION ALL
SELECT 3,N'姿势踢球他'
GO
--SELECT * FROM [t2]
-->SQL查询如下:
IF NOT OBJECT_ID('[SP_tony]') IS NULL
DROP PROC [SP_tony]
GO
CREATE PROC SP_tony(
@tb sysname
)
AS
SET NOCOUNT ON
DECLARE @Name NVARCHAR(20)
DECLARE C CURSOR FOR
SELECT Name FROM t1
OPEN C
FETCH C INTO @Name
WHILE @@FETCH_STATUS=0
BEGIN
EXEC('UPDATE ['+@tb+'] SET
Des=REPLACE(Des,'''+@name+''','''+@name+''')
WHERE CHARINDEX('''+@name+''',Des)=0
AND CHARINDEX('''+@Name+''',Des)>0')
FETCH C INTO @Name
END
CLOSE C
DEALLOCATE C
SET NOCOUNT OFF
EXEC('SELECT * FROM ['+@tb+']')
GO
--
EXEC SP_tony T2
/*
id des
----------- -------------------------------------------------------------------------------------------
(3 行受影响)
*/
--函数法:
IF NOT OBJECT_ID('[fn_tony]') IS NULL
DROP FUNCTION [fn_tony]
GO
CREATE FUNCTION [fn_tony](@s NVARCHAR(4000))
RETURNS NVARCHAR(4000)
BEGIN
SELECT @s=REPLACE(@s,name,''+name+'')
FROM t1
WHERE CHARINDEX(name,@s)>0
AND CHARINDEX(''+name+'',@s)=0
RETURN @s
END
GO
--查询
SELECT ID,dbo.fn_tony(des) DES FROM t2
需求贴:http://topic.csdn.net/u/20100419/17/888b28fe-8d79-4181-b19b-e41690723847.html?58098