declare @sql AS NVARCHAR(2000), @col varchar(7000), @usci_num varchar(100) set @col='' select @col=@col+','+name from syscolumns where id=object_id('DB_UCARCHIVE') and name<>'FRZJHM' and name<>'DZYX' and name<>'JBRZJHM'and name<>'FRZW'and name<>'FRYDDH' and name<>'FRGDDH'and name<>'FRDZYX'and name<>'FRSLFS'and name<>'LXRZJLX'and name<>'FRDZYX' and name<>'DHHM' and name<>'FRZJLX' and name<>'LXRZJHM' order by colid set @col=stuff(@col,1,1,'') --去掉第一个逗号stuff(要替换的串,第几位替换,替换的原串位数,'替换的内容') --print @col set @usci_num='1150100MA0PR2WL8Y' set @sql='select ' +@col+ ' from DB_UCARCHIVE where TYSHXYDM= ' + @usci_num exec(@sql) 执行出错,要修改哪里
时间: 2023-12-24 14:02:10 浏览: 546
在你提供的代码中,`TYSHXYDM` 的值没有使用单引号括起来,导致 SQL 语句出现语法错误。需要将 `@usci_num` 的赋值改为:
```
set @usci_num = '1150100MA0PR2WL8Y'
```
修改后的完整代码如下:
```
declare @sql AS NVARCHAR(2000), @col varchar(7000), @usci_num varchar(100)
set @col=''
select @col=@col+','+name from syscolumns where id=object_id('DB_UCARCHIVE') and name<>'FRZJHM' and name<>'DZYX' and name<>'JBRZJHM'and name<>'FRZW'and name<>'FRYDDH' and name<>'FRGDDH'and name<>'FRDZYX'and name<>'FRSLFS'and name<>'LXRZJLX'and name<>'FRDZYX' and name<>'DHHM' and name<>'FRZJLX' and name<>'LXRZJHM' order by colid
set @col=stuff(@col,1,1,'') --去掉第一个逗号stuff(要替换的串,第几位替换,替换的原串位数,'替换的内容')
--print @col
set @usci_num='1150100MA0PR2WL8Y'
set @sql='select ' +@col+ ' from DB_UCARCHIVE where TYSHXYDM= ''' + @usci_num + ''''
exec(@sql)
```
其中,`TYSHXYDM= ''' + @usci_num + '''` 使用了三个单引号,将 `@usci_num` 的值括起来,避免了 SQL 语句出现语法错误。
阅读全文