The following stored procedure dynamically determines the columns in the specified table and returns all columns that are not null, however the stored proc is returning null despite results coming back when testing the dynamic query on its own, am I handling the dynamic query return results correctly?
CREATE PROCEDURE [dbo].[spGetTables]
(
@TableName varchar(255)
,@ParamOut varchar(2000) OUTPUT
)
AS
declare @CommaString varchar(max)
set @CommaString = ''
Declare @col varchar(255), @cmd nvarchar(max)
declare @colName varchar(2000)
SET @colName = ''
DECLARE getinfo cursor for
SELECT c.name FROM sys.tables t JOIN sys.columns c ON t.Object_ID = c.Object_ID
WHERE t.Name = @TableName
OPEN getinfo
FETCH NEXT FROM getinfo into @col
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @cmd = 'IF NOT EXISTS (SELECT top 1 * FROM [' + @TableName + '] WHERE [' + @col + '] IS NULL or len([' + @col + ']) < 1) BEGIN select ''' + @col + ','' END'
exec sp_executesql @cmd, N'@Result varchar(max) out', @ParamOut out
set @ParamOut = @ParamOut + @CommaString
FETCH NEXT FROM getinfo into @col
END
PRINT 'Result: '+@ParamOut
CLOSE getinfo
DEALLOCATE getinfo
RETURN 0