动态NULL删除,转换失败但没有转换

时间:2013-12-23 21:48:52

标签: sql-server tsql

我正在尝试从表中动态删除所有NULLS。下面的脚本适用于Money数据类型,但现在在将nvarchar值ProjectName转换为数据类型int时出现'转换失败'错误。我不明白它在说什么转换。

-- Get columns to remove nulls from

SELECT c.column_id,c.name,c.system_type_id,t.name as [Type]
INTO #Temp
FROM sys.columns c
     JOIN sys.types t ON c.system_type_id = t.system_type_id
     JOIN sys.tables st ON c.object_id = st.object_id 
WHERE st.name = 'Project'
AND t.name = 'varchar'--in ('int','datetime','bit','varchar')  --'money'
ORDER BY t.name--c.column_id
SELECT * FROM #Temp

--Build SQL query to update null columns to blanks   


DECLARE @CID int = 1;
DECLARE @CName nvarchar(30);
DECLARE @SQL_STRING nvarchar(500);
DECLARE @MaxCID int = (SELECT MAX(column_id) FROM #Temp)

WHILE (@CID <= @MaxCID) 
BEGIN


SET @CName = (SELECT name  FROM #Temp t WHERE @CID = t.column_id )
SET @SQL_STRING = N'UPDATE orders.Project SET ' + @CName + ' = ISNULL('+@CName+','''');'
                EXEC sp_executesql @SQL_STRING

SET @CID = (@CID + 1)
PRINT @CID + @CName
END

drop table #Temp

1 个答案:

答案 0 :(得分:0)

您的打印行可能有问题,因为CID是Int,但CNAME是nvarchar。您可以尝试将CID强制转换为nvarchar以显示连接的输出。