Please forgive newbie's ignorance!
How do I grab the value of the output parameter in execute sp_executesql?
I can see the output but cannot get to it:
DECLARE @LastActivity nvarchar(100)
DECLARE @LastActivityDate datetime
DECLARE @sql nvarchar(MAX)
DECLARE @RowsToProcess int
DECLARE @CurrentRow int
DECLARE @SelectCol1 nvarchar(100)
DECLARE @SelectCol2 nvarchar(100)
DECLARE @SelectCol3 nvarchar(100)
DECLARE @LastDate TABLE (RowID int not null primary key identity(1,1), col4 nvarchar(MAX), col5 sql_variant)
DECLARE @table1 TABLE (RowID int not null primary key identity(1,1), col1 nvarchar(100),col2 nvarcha开发者_开发知识库r(100),col3 nvarchar(100))
INSERT into @table1 (col1,col2,col3)(SELECT t.name AS col1, c.name AS col2, m.Field1 as col3
FROM sys.columns c INNER JOIN
sys.tables t ON c.object_id = t.object_id INNER JOIN
sys.schemas s ON t.schema_id = s.schema_id INNER JOIN
dbo.MERGE_TABLES m ON m.Table_Name=t.name
WHERE c.name LIKE '%[_]DATE%' and m.[Enabled]='Y')
SET @RowsToProcess=@@ROWCOUNT
SET @CurrentRow=0
WHILE @CurrentRow<@RowsToProcess
BEGIN
SET @CurrentRow=@CurrentRow+1
SELECT @SelectCol1=col1,@SelectCol2=col2,@SelectCol3=col3 FROM @table1 WHERE RowID=@CurrentRow
SET @sql='SELECT ' + '[dbo].[ConvertToDatetime](MAX(' + @SelectCol2 + '))' + ' FROM ' + @SelectCol1 + ' Where ' + @SelectCol3 + ' = ' + '''0722607QZ'''
Declare @params as nvarchar(MAX)
Set @params = '@date sql_variant output'
Declare @date as sql_variant;
execute sp_executesql
@sql
,@params
,@date output
Select @date
INSERT into @LastDate VALUES (@sql, @date)
end
select col4,col5 from @LastDate
select col4,col5 from @LastDate gives me the SQL script in clo4 but col5 is empty! I need to store the @date as I still need to get the Max(@date)
Thanx a million.
SET @sql='set @date =('SELECT ' + '[dbo].[ConvertToDatetime](MAX(' + @SelectCol2 + '))' + ' FROM ' + @SelectCol1 + ' Where ' + @SelectCol3 + ' = ' + '''0722607QZ''' ) '
the above sql gives me error: Incorrect syntax near '.'
SET @sql='set @date =(SELECT [dbo].[ConvertToDatetime](MAX( + @SelectCol2 + ))
FROM @SelectCol1 Where @SelectCol3 ''=0722607QZ'' ) '
The above sql gives the error: Must declare the scalar variable "@SelectCol2"
SET @sql='SELECT ' + @date + '=convert(nvarchar(100), [dbo].[ConvertToDatetime](MAX(' + @SelectCol2 + ')))' + ' FROM ' + @SelectCol1 + ' Where ' + @SelectCol3 + ' = ' + '''0722607QZ'''
the above produces the error : Implicit conversion from data type sql_variant to nvarchar is not allowed. Use the CONVERT function to run this query.
SET @sql='SELECT ' + @date + '=convert(nvarchar(MAX),(MAX(' + @SelectCol2 + '))' + ' FROM ' + @SelectCol1 + ' Where ' + @SelectCol3 + ' = ' + '''0722607QZ'''
the above produces no error but all output is NULL, no values.
Your syntax looks ok but you never assign to the output variable @date hence no value.
Instead of;
SET @sql='SELECT ...'
You need;
SET @sql='set @date = (SELECT ...'
Can't you use a better type than sql_variant
?
精彩评论