日期:2014-05-18 浏览次数:20631 次
create table tggt(网点名称 varchar(20), 期初余额 int, 本期发生 int,g int) insert tggt select '北京', 1000, 5000,1 union all select '上海', 2000, 6000,2 go CREATE FUNCTION udf_getvalue(@v VARCHAR(20),@s VARCHAR(20)) RETURNS VARCHAR(20) AS BEGIN DECLARE @a TABLE(NAME VARCHAR(100),colid INT) DECLARE @Str VARCHAR(1000) DECLARE @Order INT ,@I INT INSERT @a SELECT NAME,colid FROM syscolumns s WHERE id=OBJECT_ID('tggt') SELECT @Order=[Order] FROM ( SELECT NAME,[ORDER]=(SELECT COUNT(1) FROM @a WHERE colid<=a.colid) FROM @a a ) aa WHERE NAME=@s SELECT @Str=ltrim(isnull(网点名称,0))+','+ltrim(isnull(期初余额,0))+','+ltrim(isnull(本期发生,0))+','+ltrim(isnull(g,0)) FROM tggt WHERE 网点名称=@v SET @I=1 WHILE @I<@Order SELECT @Str=STUFF(@Str,1,CHARINDEX(',',@Str),''),@I=@I+1 RETURN LEFT(@str,CHARINDEX(',',@Str+',')-1) END GO SELECT * FROM tggt SELECT dbo.udf_getvalue('北京','g') --result /*网点名称 期初余额 本期发生 g -------------------- ----------- ----------- ----------- 北京 1000 5000 1 上海 2000 6000 2 (所影响的行数为 2 行) -------------------- 1 (所影响的行数为 1 行) */
------解决方案--------------------
if object_id('udf_getvalue','FN') is not null drop function udf_getvalue go create function udf_getvalue(@name varchar(20),@colname varchar(20)) returns int as begin DECLARE @row varchar(1000) SET @row = (SELECT * FROM tb where 网点名称 = @name FOR XML PATH) return CAST(SUBSTRING(@row, CHARINDEX('<'+@colname+'>',@row)+LEN('<'+@colname+'>'), CHARINDEX('</'+@colname+'>',@row)-CHARINDEX('<'+@colname+'>',@row)-LEN('<'+@colname+'>') ) AS INT) end GO select dbo.udf_getvalue('北京','本期发生'),dbo.udf_getvalue('上海','期初余额') ----------- ----------- 5000 2000 (1 行受影响)