Created
November 14, 2013 11:43
-
-
Save codingawayy/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+
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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