Manipulate column names in a SQL Server table

I have two questions regarding how to manipulate column names in SQL Server. Is there a command to turn the names of columns in a table into variables, and is there a command to rename columns, as well? I have attempted the latter, but it does not work in conjunction with Visual Basic programming.

    Requires Free Membership to View

    By submitting your registration information to SearchSQLServer.com you agree to receive email communications from TechTarget and TechTarget partners. We encourage you to read our Privacy Policy which contains important disclosures about how we collect and use your registration and other information. If you reside outside of the United States, by submitting this registration information you consent to having your personal data transferred to and processed in the United States. Your use of SearchSQLServer.com is governed by our Terms of Use. You may contact us at [email protected].

You can use the following query to get a list of columns for a given table and use it to populate variables:

SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.Columns
WHERE TABLE_NAME = 'Address'

You can rename a column using the following example:

EXECUTE sp_rename N'dbo.aaa.NewColumnName', N'NewColumnName2', 'COLUMN'

You can execute it from VB.NET, as well, by using the SqlCommand object and setting the CommandText property to the SQL code you want to execute. For a similar example, look at this expert answer on restoring SQL Server databases in VB.NET.

This was first published in October 2008

Join the conversationComment

Share
Comments

    Results

    Contribute to the conversation

    All fields are required. Comments will appear at the bottom of the article.