- SQL code
select substring('xie[谢]',charindex('[','xie[谢]')+1,charindex(']','xie[谢]')-charindex('[','xie[谢]')-1)
把上边放到SQL查询里边,看起来太繁琐了,xie[谢] 是字段。
请问,如果要写成自定义函数,怎么写? 后边怎么引用
谢谢
------解决方案--------------------
- SQL code
goif OBJECT_ID('fun_tracy')is not nulldrop function fun_tracygocreate function fun_tracy (@col varchar(20))returns varcharasbegindeclare @str varchar(10)select @str=substring(@col,charindex('[',@col)+1,charindex(']',@col)-charindex('[',@col)-1) from tbl1return @strend
------解决方案--------------------
写个存储过程可以吧
------解决方案--------------------
------解决方案--------------------
------解决方案--------------------
------解决方案--------------------
------解决方案--------------------
- SQL code
CREATE PROCEDURE protest@str varchar(100),@RESULT varchar(1000) outputASSET @RESULT=substring(@str,charindex('[',@str)+1,charindex(']',@str)-charindex('[',@str)-1)GO
------解决方案--------------------
- SQL code
--如果诸如xie[谢]之类的是个字段,在表中。create table tb(col varchar(50))insert into tb values('xie[谢]')insert into tb values('xie[谢谢]')go--直接使用substring + charindex完成select col , new_col = (substring(col , charindex('[' , col) + 1 , charindex(']' , col) - charindex('[' , col) - 1)) from tb where charindex('[' , col) < charindex(']' , col)/*col new_col -------------------------------------------------- -------------------------------------------------- xie[谢] 谢xie[谢谢] 谢谢(所影响的行数为 2 行)*/--如果你要用函数完成gocreate function dbo.f_str(@col varchar(50)) returns varchar(50)asbegin declare @str varchar(50) if charindex('[' , @col) < charindex(']' , @col) set @str = (substring(@col , charindex('[' , @col) + 1 , charindex(']' , @col) - charindex('[' , @col) - 1)) else set @str = '' return @strendgo--调用函数select col , new_col = dbo.f_str(col) from tb /*col new_col -------------------------------------------------- -------------------------------------------------- xie[谢] 谢xie[谢谢] 谢谢(所影响的行数为 2 行)*/drop function dbo.f_strdrop table tb