存储过程中的动态SQL - 与多列连接

时间:2013-04-01 16:23:33

标签: sql-server stored-procedures

我正在尝试创建一个视图,其中列连接以生成导入行。

以下是我的陈述:

SET NOCOUNT ON;
declare @SQL as varchar(4000)
        --@CD as date

--set @CD = convert(varchar(30), cast(getdate() as date), 110)


    -- Insert statements for procedure here
set @SQL = 'CREATE VIEW vw_GCS_Export
    As
    select division, [primary image id],[Item Number], [Brand Name],[Marketing Description],
    [Colours]as Colors,[Live Date],[Sample Type],substring([FileName],charindex('+ CHAR(39) + '_' + CHAR(39) +',[FileName],1)+1,CHARINDEX('+ CHAR(39) + '.' + CHAR(39) +',[FileName],1)-5) as BatchID,
    '+ CHAR(39) + '670' + CHAR(39) +' as Status, [Primary image ID] + '+ CHAR(39) + '_P' + CHAR(39) +' as [Shot Name],
    Cast(Null as varchar(50))as [Swatch/Variation],Cast(Null as varchar(50))as [Alternate Shot],[UserName],''' + CAST(convert(date,Sysdatetime(),110)as varchar(10)) + ''' as [Import Date],
    Cast(Null as varchar(50))as [Return Instructions],Cast(Null as varchar(50))as [Rush Request], DATEADD(WEEKDAY,-5,[live date]) as [ImageDeliveryDate],
    '+ CHAR(39) + 'Division '+ CHAR(39) + '+ [division] +'+ CHAR(39) + ' * ' + CHAR(39) +' + [UserName] as JobName
    from Sheet1$'


EXEC (@SQL)
select * from vw_GCS_Export

END

当我执行存储过程时,出现错误:

  

将数据类型varchar转换为float时出错。

我是否需要使用强制转换将列定义为nvarchar(50)或类似的东西?

1 个答案:

答案 0 :(得分:0)

n此问题中缺少大量信息,例如[Sheet1 $]中列的数据类型。但是,我可以给你一个一般的解释。每当表达式尝试将浮点值与字符串值连接时,您将收到此错误。您可能期望自动转换将float转换为字符串然后连接,但实际上发生的是MSSQL尝试将字符串转换为数值然后将其添加到float。正如Love2Learn所说,你需要明确地将数值转换/转换为字符串,例如

cast([Primary image ID] as varchar(max)) + '_P' as [Shot Name]
'Division '+ cast([division] as varchar(max)) +' * ' + [UserName] as JobName