错误:操作数数据类型varchar对除运算符无效

时间:2014-08-11 12:10:06

标签: sql-server

我正在使用动态存储过程

if @ReportType = 'Daily Batch'
begin 
   set @SelectionList= 'select ''' + @tag0 + ''' as Tag0 , ''' + @tag1 + ''' as Tag1 , ''' +  @tag2 + ''' as Tag2 , ''' +  @tag3 + ''' as Tag3 , ''' +  @tag4 + ''' as Tag4 , ''' +  @tag5 + ''' as Tag5 
 , ''' +  @tag6 + ''' as Tag6 , ''' +  @tag7 + ''' as Tag7 , ''' +  @tag8 + ''' as Tag8 , ''' +  @tag9 + ''' as Tag9 , ''' +  @tag10 + ''' as Tag10 , ''' +  @tag11 + ''' as Tag11
 , ' +  @value0 + ' as Value0 , ' +  @value1 + ' as Value1, ' +  @value2 + ' as Value2 , ' +  @value3 + ' as Value3 , ' +  @value4 + ' as Value4 , ' +  @value5 + ' as Value5
 , ' +  @value6 + ' as Value6 , ' +  @value7 + ' as Value7 , ' +  @value8 + ' as Value8 , ' +  @value9 + ' as Value9 , ' +  @value10 + ' as Value10 , ' +  @value11 + ' as Value11         
 , RefProductWgt1, RefProductWgt2, RefProductWgt3, RefProductWgt4, RefProductWgt5, RefProductWgt6, RefProductWgt7, RefProductWgt8, 
                     RefProductWgt9, RefProductWgt10, ProductCount, PassCount, RejectCount, UnderWgts, OverWgts, DoubleCount, ReportId, StartDate as GroupColumn
 FROM  BatchMaster    
  WHERE SUBSTRING(StartDate, 0, charindex('/' , StartDate, 0))='''+ @startdate+''') AND (DeviceId = '''+@devid+''')     

 end

 exec (@SelectionList)

@SelectionList数据类型为nvarchar(3000),我只想从DateTime列中提取数据...

但是它显示了这个错误:

  

操作数数据类型varchar对除运算符无效。

此处'/'用作字符不分,因为在我的专栏DateStoreLikedd-mm-yy/HH:MM:SS)中,我试图仅提取'/'符号之前的日期部分< / p>

1 个答案:

答案 0 :(得分:1)

您收到的错误是因为您需要在斜线的每一边都有两个单引号:

...WHERE SUBSTRING(StartDate, 0, charindex(''/'' , StartDate, 0))='''+ @startdate+''') AND (DeviceId = '''+@devid+''')     

例如,以下两个查询将返回“5”作为结果:

SELECT charindex('/' , 'this/string', 0)

DECLARE @sql VARCHAR (55) = 'SELECT charindex(''/'' , ''this/string'', 0)'
EXEC(@sql)

如果要在字符串中显示单引号,则需要使用两个单引号。为了演示这一点,您可以运行以下命令:

SELECT '' --This will return an empty string

SELECT '''' --This will return a single quotation mark