我的查询有什么问题?

时间:2015-05-15 06:23:02

标签: sql

@tablen1 varchar(32),
@tablen2 varchar(32)
as
DECLARE @sqlCommand varchar(1000)
DECLARE @table1 varchar(MAX)
DECLARE @table2 varchar(MAX)
DECLARE @table3 varchar(MAX)
set @table1 = @tablen1
set @table2 = @tablen2
set @table3 = 'AB_Dispensing'
SET @sqlCommand = 'SELECT ' +@table1+'.ATM_ID,'+@table1+'.LE,'+@table2+'.LE,'+@table3+'.Dispensed''
FROM    '+@table1+','+@table2+','+@table3+'

where '+@table1+'.atm_id = '+@table2+'.atm_id''''AND''' +@table3+'.ATM_ID = '+@table1+'.ATM_ID'
    EXEC (@sqlCommand)

当我像这样运行这个查询时:

exec AB_DIF _3_0_PM_14_MAY,_3_2_PM_14_MAY

我收到此消息

  

'AB_Dispensing'附近的语法不正确。

1 个答案:

答案 0 :(得分:3)

打印动态sql并检查它是否有效,总是很方便。

如果您将't1''t2'作为输入传递给您的代码并打印@SQLCommand,则会获得:

SELECT t1.ATM_ID,t1.LE,t2.LE,AB_Dispensing.Dispensed'
FROM    t1,t2,AB_Dispensing

where t1.atm_id = t2.atm_id''AND'AB_Dispensing.ATM_ID = t1.ATM_ID

请注意导致此SQL无效的'。您需要删除'.Dispensed''

中使用的不必要的''''AND'''

这就是你的sql应该是什么。

declare @tablen1 varchar(32) = 't1',
@tablen2 varchar(32) = 't2'

DECLARE @sqlCommand varchar(1000)
DECLARE @table1 varchar(MAX)
DECLARE @table2 varchar(MAX)
DECLARE @table3 varchar(MAX)
set @table1 = @tablen1
set @table2 = @tablen2
set @table3 = 'AB_Dispensing'
SET @sqlCommand = 'SELECT ' +@table1+'.ATM_ID,'+@table1+'.LE,'+@table2+'.LE,'+@table3+'.Dispensed
FROM    '+@table1+','+@table2+','+@table3+'

where '+@table1+'.atm_id = '+@table2+'.atm_id AND ' +@table3+'.ATM_ID = '+@table1+'.ATM_ID'
--print @SQlCommand
    EXEC (@sqlCommand)