How can I get column names from a table in SQL Server?

You can obtain this information and much, much more by querying the Information Schema views. This sample query: SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = N’Customers’ Can be made over all these DB objects: CHECK_CONSTRAINTS COLUMN_DOMAIN_USAGE COLUMN_PRIVILEGES COLUMNS CONSTRAINT_COLUMN_USAGE CONSTRAINT_TABLE_USAGE DOMAIN_CONSTRAINTS DOMAINS KEY_COLUMN_USAGE PARAMETERS REFERENTIAL_CONSTRAINTS ROUTINES ROUTINE_COLUMNS SCHEMATA TABLE_CONSTRAINTS TABLE_PRIVILEGES TABLES VIEW_COLUMN_USAGE VIEW_TABLE_USAGE VIEWS

Parameterize an SQL IN clause

You can parameterize each value, so something like: string[] tags = new string[] { “ruby”, “rails”, “scruffy”, “rubyonrails” }; string cmdText = “SELECT * FROM Tags WHERE Name IN ({0})”; string[] paramNames = tags.Select( (s, i) => “@tag” + i.ToString() ).ToArray(); string inClause = string.Join(“, “, paramNames); using (SqlCommand cmd = new SqlCommand(string.Format(cmdText, inClause))) { … Read more

How to check if a column exists in a SQL Server table

SQL Server 2005 onwards: IF EXISTS(SELECT 1 FROM sys.columns WHERE Name = N’columnName’ AND Object_ID = Object_ID(N’schemaName.tableName’)) BEGIN — Column Exists END Martin Smith’s version is shorter: IF COL_LENGTH(‘schemaName.tableName’, ‘columnName’) IS NOT NULL BEGIN — Column Exists END

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)