-1

这是我在存储过程中的动态 sql

BEGIN

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

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],
    '  + convert(varchar(50), ' + ' +  CHAR(39) + 'Division ' + CHAR(39) +' + [Division] + '+ CHAR(39) + ' * ' + CHAR(39) +' + [UserName] ) as JobName 
    from Sheet1$'


EXEC @SQL
select * from vw_GCS_Export

END

我在执行时遇到错误

Incorrect syntax near the keyword 'EXEC'.

我不确定为什么。SQL 语句中似乎没有任何错误。

4

3 回答 3

5

你需要括号:

EXEC (@sql)

请参阅如何从变量运行生成的 SQL?

于 2013-04-01T19:04:06.427 回答
2

您的实际问题在这里:

 '  + convert(varchar(50), ' 

你有一个CONVERT没有第二个论点。可能是您打算CONVERT在动态 SQL 中包含 或者您打算拥有这部分

' + [UserName] ) as JobName

作为你的结束,CONVERT但在任何一种情况下,它都不会编译并且你的语法被破坏了。

于 2013-04-01T20:01:51.307 回答
0

这是我最终得到的结果:

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

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) +'+ cast([Division] as varchar(50)) + '+ CHAR(39) + ' * ' + CHAR(39) + ' + [UserName] as JobName 
    from Sheet1$'


    EXEC (@SQL)
    select * from vw_GCS_Export

关键是我不能对整个字符串使用强制转换,我只能将它放在浮动字段 [Division] 上。我感谢所有帮助 FreshPrinceofSO

于 2013-04-01T21:13:54.920 回答