T-SQL has the type SYSNAME for storing things like table names:
The sysname data type is used for table columns, variables, and stored
procedure parameters that store object names. The exact definition of
sysname is related to the rules for identifiers. Therefore, it can
vary between instances of SQL Server. sysname is functionally the same
as nvarchar(128) except that, by default, sysname is NOT NULL. In
earlier versions of SQL Server, sysname is defined as varchar(30).
So try declaring your variable like this:
DECLARE @tableName SYSNAME;
Using the VARCHAR(100) declaration, as suggested in other answers, will fail if the table name contains characters outside your current code page or is longer than 100 characters.
This excerpt from SQL Server's rules for identifiers describes the form of a table name:
The first character must be one of the following:
A letter as defined by the Unicode Standard 3.2. The Unicode
definition of letters includes Latin characters from a through z, from
A through Z, and also letter characters from other languages.
The underscore (_), at sign (@), or number sign (#).
Certain symbols at the beginning of an identifier have special meaning
in SQL Server. A regular identifier that starts with the at sign
always denotes a local variable or parameter and cannot be used as the
name of any other type of object. An identifier that starts with a
number sign denotes a temporary table or procedure. An identifier that
starts with double number signs (##) denotes a global temporary
object. Although the number sign or double number sign characters can
be used to begin the names of other types of objects, we do not
recommend this practice.
Some Transact-SQL functions have names that start with double at signs
(@@). To avoid confusion with these functions, you should not use
names that start with @@.
Subsequent characters can include the following:
Letters as defined in the Unicode Standard 3.2.
Decimal numbers from either Basic Latin or other national scripts.
The at sign, dollar sign ($), number sign, or underscore.
The identifier must not be a Transact-SQL reserved word. SQL Server
reserves both the uppercase and lowercase versions of reserved words.
Embedded spaces or special characters are not allowed.
Supplementary characters are not allowed.
See the documentation links in my answer for more information.
select top 2 table_name from INFORMATION_SCHEMA.TABLES order by table_name ascnot good enough?PRINTa result set. You might want to print a table name rather than select it if you are writing a script that produces another script as output.