Skip to content

Instantly share code, notes, and snippets.

@niaher
Created November 14, 2013 11:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save niaher/7465460 to your computer and use it in GitHub Desktop.
Save niaher/7465460 to your computer and use it in GitHub Desktop.
Here is the SQL code to print a row of from any table. All you have to do is modify the @tableName and @whereClause variables. Works only in MS SQL 2005+
DECLARE @tableName varchar(100)
DECLARE @whereClause varchar(100)
SET @tableName = 'Customers'
SET @whereClause = 'WHERE id = 999'
DECLARE @table TABLE(id int identity(1, 1), name varchar(100))
INSERT INTO @table (name)
SELECT name FROM sys.columns WHERE object_id = OBJECT_ID(@tableName)
DECLARE @i int
DECLARE @rowCount int
SELECT @i = MIN(id), @rowCount = MAX(id) FROM @table
DECLARE @rowString varchar(MAX)
SET @rowString = ''
WHILE (@i <= @rowCount)
BEGIN
DECLARE @columnName varchar(100)
SELECT @columnName = name FROM @table WHERE id = @i
DECLARE @columnValueTable TABLE(name varchar(100))
INSERT INTO @columnValueTable
EXEC ('SELECT ' + @columnName + ' FROM ' + @tableName + ' ' + @whereClause)
DECLARE @columnValue varchar(100)
SELECT @columnValue = name FROM @columnValueTable
IF (@columnValue IS NULL) SET @columnValue = 'NULL'
SET @rowString = @rowString + @columnName + ': ' + @columnValue + CHAR(10)
SET @i = @i + 1
END
-- You can also use SELECT instead of PRINT.
PRINT @rowString
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment