截取字符串 表名
dbo.tab1
dbo.[tab1]
[dbo].[tab1]
这样写表名都是可以的
假设上面三个都是字符串, 怎么才能截取到真正的表名tab1?
相当于是要写一个函数
create function dbo.GetTableName( @tableName nvarchar(250))returns nvarchar(150)as--.........
select PATINDEX ( '%[%]', '[schema1].[mytab2]' )
DECLARE @str VARCHAR(20)SET @str = '[dbo].[tab1]'IF (CHARINDEX('.',@str) > 0) SET @str = STUFF(@str,1,CHARINDEX('.',@str),'')IF (CHARINDEX('[',@str) > 0) SET @str = STUFF(@str,1,CHARINDEX('[',@str),'')IF (CHARINDEX(']',@str) > 0) SET @str = LEFT(@str,CHARINDEX(']',@str)-1)SELECT @str
[解决办法]
if not object_id('tb') is null drop table tbGoCreate table tb([col] nvarchar(18))Insert tbselect N'[schema1].[mytab2]' union allselect N'[myschema].[tab1]' union allselect N'dbo.tab1'GoSelect replace(replace(right([col],len([col])-charindex('.',[col])),']',''),'[','')from tb/*----------------------------------------------------------------------------------------------------------------mytab2tab1tab1(3 個資料列受到影響)*/
[解决办法]
-- sql 2005select PARSENAME('dbo.tab1',1);-- sql 2000declare @tabname sysname;set @tabname='dbo.tab1';select right(@tabname,charindex('.',reverse(@tabname))-1);