日期:2014-05-19  浏览次数:20531 次

如何从select语句中截取表名
select   *   from                       tableName           where   id   =   "1 ";
像这样一句select语句,如何才能截取到 "tableName "呢?

------解决方案--------------------
declare @aa nvarchar(4000)
set @aa= 'select * from tableName where id = "1 "; '
select replace(substring(@aa,CHARINDEX( ' from ',@aa)+6,CHARINDEX( ' where ',@aa)-CHARINDEX( ' from ',@aa)-6), ' ', ' ')


--result
tableName

------解决方案--------------------
declare @aa nvarchar(4000)---借用
set @aa= 'select * from tableName where id = "1 "; '
select @aa=ltrim(stuff(@aa,1,charindex( 'from ',@aa)+3, ' '))
select left(@aa,charindex( ' ',@aa)-1)
合并成一句(只考虑from,没有where也行)
select left(ltrim(stuff(@aa,1,charindex( 'from ',@aa)+3, ' ')),charindex( ' ',ltrim(stuff(@aa,1,charindex( 'from ',@aa)+3, ' ')))-1)