Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get table/view name (i.e. remove schema prefix)

Tags:

c#

sql

t-sql

Given one of the following strings (which represent a table/view name in SQL Server):

var x = "[my-Table.request]"; 
var x = "[dbo].[my-Table.request]";
var x = "dbo.[my-Table.request]";

I would like to get the table name (by C# code): my-Table.request

Any ideas? have i missed any possible representations here?

like image 979
Yosi Dahari Avatar asked Dec 18 '25 20:12

Yosi Dahari


2 Answers

Quite simply via PARSENAME in TSQL:

PARSENAME(@x, 1)

With your edit where you want it in C#, you'd basically have to write it from scratch in C#, tokenizing by the ., [, ]. AFAIK there is no pre-canned implementation that does this for you.

like image 137
Marc Gravell Avatar answered Dec 21 '25 12:12

Marc Gravell


If you're doing this on the SQL side, there's a PARSENAME function for doing exactly that.

E.g. PARSENAME(x,1) returns the object (in this case table) name. PARSENAME(x,2) returns the schema, etc.

like image 45
Damien_The_Unbeliever Avatar answered Dec 21 '25 12:12

Damien_The_Unbeliever