SQL无效的列名错误

时间:2017-04-03 20:32:54

标签: sql sql-server

这是有效的查询;

@tc varchar(11),
@urun nvarchar(50),
@islem nvarchar(20),
@ilk_agirlik nvarchar(4),
@son_Agirlik nvarchar(4)
AS
BEGIN
SET NOCOUNT ON;
DECLARE @tabloadi NVARCHAR(15)
declare @sutunadi1 nvarchar(max)
set @sutunadi1 = @urun+N'_'+@islem+N'_ilk'
declare @sutunadi2 nvarchar(max)
set @sutunadi2 = @urun+N'_'+@islem+N'_son'
SET @tabloadi=@tc
IF EXISTS(SELECT *
            FROM INFORMATION_SCHEMA.COLUMNS
            WHERE TABLE_NAME=@tabloadi
                AND COLUMN_NAME=@sutunadi1)
BEGIN 
    declare @sql nvarchar(max)
    SET @Sql = N'insert into dbo.' + QUOTENAME(@Tc)
      + N'(' + QUOTENAME(@sutunadi1)+ N',' + QUOTENAME(@sutunadi2) + N',   gun, ay, yil, saat, dakika) ' 
      + N'VALUES (' + @ilk_agirlik+ N',' + @son_agirlik + N',' + convert(varchar(2),day(GETDATE())) + N',' + convert(varchar(2),month(GETDATE())) + N',' + convert(varchar(4),year(GETDATE()))  + N',' + convert(varchar(2),datepart(hh,GETDATE())) + N',' + convert(varchar(2),datepart(mi,GETDATE())) + N')'
   EXECUTE sp_executesql @Sql 
END     

当我添加了两列名称为urun和islem的列时 我刚刚更改了这段代码;

    SET @Sql = N'insert into dbo.' + QUOTENAME(@Tc)
      + N'(' + QUOTENAME(@sutunadi1)+ N',' + QUOTENAME(@sutunadi2) + N',   gun, ay, yil, saat, dakika, urun, islem) ' 
      + N'VALUES (' + @ilk_agirlik+ N',' + @son_agirlik + N',' + convert(varchar(2),day(GETDATE())) + N',' + convert(varchar(2),month(GETDATE())) + N',' + convert(varchar(4),year(GETDATE()))  + N',' + convert(varchar(2),datepart(hh,GETDATE())) + N',' + convert(varchar(2),datepart(mi,GETDATE())) + N',' + @urun + N',' + @islem + N')'

它产生的错误是"无效的列名" 错误是什么,我刚刚为工作查询添加了两列????

2 个答案:

答案 0 :(得分:0)

尝试用以下代码替换最后一行:

+ N'VALUES (' + @ilk_agirlik+ N',' + @son_agirlik + N',' + convert(varchar(2),day(GETDATE())) + N',' + convert(varchar(2),month(GETDATE())) + N',' + convert(varchar(4),year(GETDATE()))  + N',' + convert(varchar(2),datepart(hh,GETDATE())) + N',' + convert(varchar(2),datepart(mi,GETDATE())) + N',''' + @urun + N''',''' +@islem + N''')'

答案 1 :(得分:0)

它解决了。感谢Kannan Kandasamy解决方案,当我使用char(39)并将其连接解决时。

  SET @Sql = concat('insert into dbo.', QUOTENAME(@Tc),
         '(', QUOTENAME(@sutunadi1),',',QUOTENAME(@sutunadi2) ,', gun, ay,   yil, saat, dakika, urun, islem) ' 
          ,'VALUES (' , @ilk_agirlik,',' , @son_agirlik ,',',convert(varchar(2),day(GETDATE())) ,',',convert(varchar(2),month(GETDATE())) ,',' ,  convert(varchar(4),year(GETDATE()))  ,',' , convert(varchar(2),datepart(hh,GETDATE())) ,',' , convert(varchar(2),datepart(mi,GETDATE())) ,',' , char(39), @urun,char(39),',',  char(39),@islem,char(39) ,')')