CREATE FUNCTION Split ( @SourceSql varchar(8000), @StrSeprate varchar(10) ) RETURNS @temp TABLE(F1 VARCHAR(100)) AS BEGIN DECLARE @i INT SET @SourceSql=rtrim(ltrim(@SourceSql)) SET @i=charindex(@StrSeprate,@SourceSql) WHILE @i>=1 BEGIN INSERT @temp VALUES(left(@SourceSql,@i-1)) SET @SourceSql=substring(@SourceSql,@i+1,len(@SourceSql)-@i) SET @i=charindex(@StrSeprate,@SourceSql) END IF @SourceSql<>'' INSERT @temp VALUES(@SourceSql) RETURN END
CREATE FUNCTION GetTitle(@NoAll NVARCHAR(2000)) RETURNS NVARCHAR(2000) AS BEGIN DECLARE @result VARCHAR(2000) SET @result='' DECLARE getTitle CURSOR FOR SELECT * FROM split(@NoAll,',') OPEN getTitle
DECLARE @No SYSNAME
FETCH FROM getTitle INTO @No WHILE @@fetch_status=0 BEGIN
SET @result=@result+(SELECT Title FROM Table1 WHERE No=@No)+',' FETCH FROM getTitle INTO @No END CLOSE getTitle SET @result= substring(@result,0,len(@result))
DEALLOCATE getTitle
RETURN @result END
最后执行下面语句出想要的结果,如下:
1 2 3 4 5
SELECT NoAll, dbo.GetTitle(No) AS TitleAll FROM Table2