I’m coding in C# in ASP.NET environment and I need to write a function that takes SQL Server database table and gives it another name.
So from SQL standpoint I need to do this:
EXEC sp_rename 'OldTableName', 'NewTableName';
But the problem is that at times the (old) table name supplied to my function can be something like this: [dbo].[OldTableName] and as far as I can understnad the brackets (‘[‘ and ‘]’) are not the part of the name itself, as well as the “dbo” part.
So how to handle such situation?
EDIT: I was able to come up with C# code to remove brackets (needs to be checked though):
for (int i = 0; i < strTableName.Length; i++)
{
if (strTableName[i] == '[' ||
strTableName[i] == ']')
{
int j = i;
for (; j < strTableName.Length && strTableName[j] == strTableName[i]; j++) ;
int nRepeatCnt = j - i;
int nNumKeep = nRepeatCnt / 2;
int nNumRemove = nRepeatCnt - nNumKeep;
strTableName = strTableName.Remove(i, nNumRemove);
i += nNumKeep - 1;
}
}
When using SQL Server internal (system) stored procedures and functions (
sp_rename,sp_help,OBJECT_ID, …), there is no need to remove or add delimiters and qualifiers (‘[‘ and ‘]’ or default schema name such as ‘dbo’), because these functions parse the identifier names and infer the actual name. Also there are some situations that you require to use the delimiters (When they are not Regular Identifiers. See Identifiers).For example when renaming
dbo.MyTabletodbo.NewTable, all of these command are valid:But be noticed that the new name you specify as the second parameter of the
sp_renamewill not be parsed, and the stored procedure will set the object name exactly as what you specified:This changes
MyTableto[dbo].NewTable, and your qualified table name is exactlydbo.[dbo].NewTable! Accessing this new table with this name, is a little tricky:But when accessing object names in SQL Server system tables (like
sys.table,sys.columns, …), you should not use delimiters and qualifiers, because the identifiers in those table are stored as character strings:OBJECT_ID()is a system function and parses the object name, butOrderIDshould be specified as the exact column name (case insesitive).