我想檢查一個表的列是否包含空值,如果是,則分配0值。我有問題,因爲那裏存在UniqueIdentifier列。所以我更改我的代碼以分配'0'值。但是現在當有DateTime列時,我遇到了問題。 下面是代碼:SQL Server:從字符串轉換日期和/或時間時轉換失敗
Select @sql = @sql + 'Case when IsNull(i.[' + Column_Name +
'],''0'') = IsNull(d.[' + Column_name + '],''0'') then ''''
else ' + quotename(Column_Name, char(39)) + ' + '',''' + ' end +'
from information_schema.columns
where table_name = 'Users' and column_name <>'rowguid' and column_name <>'modifieddate'
另一個失敗的嘗試:
Select @sql = @sql +
'Case
when IsDate(i.['+Column_Name+']) =1 and IsDate(d.['+Column_Name+']) =1 and IsNull(i.[' + Column_Name + '],1/1/1900) = IsNull(d.[' + Column_name + '],1/1/1900)
then ''''
when IsNull(i.[' + Column_Name + '],''0'') = IsNull(d.[' + Column_name + '],''0'')
then ''''
else ' + quotename(Column_Name, char(39)) + ' + '',''' + ' end +'
from information_schema.columns
where table_name = 'Users' and column_name <>'rowguid' and column_name <>'modifieddate'
全碼:
if @Action = 'U'
BEGIN
Select @sql = @sql +
'Case when IsNull(i.[' + Column_Name +
'],' + CASE DATA_TYPE
WHEN 'int' THEN '0'
WHEN 'bigint' THEN '0'
WHEN 'tinyint' THEN '0'
WHEN 'uniqueidentifier' THEN '''0'''
WHEN 'varchar' THEN CHAR(39) + '-' + CHAR(39)
WHEN 'nvarchar' THEN CHAR(39) + '-' + CHAR(39)
WHEN 'date' THEN CHAR(39) + '1/1/1900' + CHAR(39)
WHEN 'datetime' THEN CHAR(39) + '1/1/1900 00:00:00' + CHAR(39)
ELSE ''
END + ') = IsNull(d.[' + Column_name + '],'+
CASE DATA_TYPE
WHEN 'int' THEN '0'
WHEN 'bigint' THEN '0'
WHEN 'tinyint' THEN '0'
WHEN 'uniqueidentifier' THEN '''0'''
WHEN 'varchar' THEN CHAR(39) + '-' + CHAR(39)
WHEN 'nvarchar' THEN CHAR(39) + '-' + CHAR(39)
WHEN 'date' THEN CHAR(39) + '1/1/1900' + CHAR(39)
WHEN 'datetime' THEN CHAR(39) + '1/1/1900 00:00:00' + CHAR(39)
ELSE ''
END + ') then ''''
else ' + quotename(Column_Name, char(39)) + ' + '',''' + ' end +'
from information_schema.columns
where table_name = 'Users' and column_name <>'rowguid' and column_name <>'modifieddate'
--Define output parameter
set @ParmDefinition = '@OutString varchar(max) OUTPUT'
--Format sql
set @sql = 'Select @OutString = '
+ Substring(@sql,1 , len(@sql) -1) +
' From dbo.Users i ' --Will need to be updated for target schema
+ ' inner join #tempTrigT d on
i.id = d.id' --Will need to be updated for target schema
--Execute sql and retrieve desired column list in output parameter
exec sp_executesql @sql, @ParmDefinition, @OutString OUT
你將不得不選擇一個更合適的默認值 - 一個日期。 –
我想動態,因爲有不同的列(INT,日期時間,GUID等) – aggicd
數據庫允許什麼是比你想要的更相關。 –