SQL两表匹配,将A表的指定字段所有内容根据条件更新B表指定字段的所有内容

  
<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ --> t1 id name 1 2 3 4 她 t2 id des 1 偶然间水立方我是你的 2 苏利文哦她上电缆附件你塑料袋解放他 3 姿势踢球他

<!-- Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/ -->--结果:
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 <X86> (Build 2600: Service Pack 3)

--------------------------------------------------------------------------

--> 生成测试数据表: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+''',''<a href="#">'+@name+'</a>'')

WHERE CHARINDEX(''<a href="#">'+@name+'</a>'',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

----------- -------------------------------------------------------------------------------------------

1 偶然间水立方<a href="#"></a><a href="#"></a>

2 苏利文哦<a href="#"></a>上电缆附件<a href="#"></a>塑料袋解放<a href="#"></a>

3 姿势踢球<a href="#"></a>

(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,'<a href="#">'+name+'</a>')

FROM t1

WHERE CHARINDEX(name,@s)>0

AND CHARINDEX('<a href="#">'+name+'</a>',@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

你可能感兴趣的:(sql,C++,SQL Server,C#,Go)