我想创建一个 存储过程 ,我想在表中插入值。但是我不知道我必须在哪个字段中插入值,而在 运行时,我将决定应在哪个字段中插入值 。我想做的是
insert into Tablename(@ColumnName, Description) values (@ColumnValue, @MH_Description)
如上例所示,是否可以在存储过程中传递这种类型的参数?
我也想使用条件
声明@Query nvarchar(4000)声明@ Query1 nvarchar(4000)声明@ParmDefinition nvarchar(500); set @Query = ' insert into tbl_temp(' + quotename(@ColumnName) +',Description) values (@ColumnValue, @Description)' set @Query1 = ' update tbl_temp set' + quotename(@ColumnName) +'=@ColumnValue, Description=@Description’ set @ParmDefinition = N’@ColumnValue varchar(100),@Description varchar(100)’ if exists(select ‘true’ from tbl_temp where quotename(@ColumnName)=@ColumnValue) begin exec sp_executesql @Query1, @ParmDefinition, @ColumnValue = @ColumnValue, @Description = @Description end else begin exec sp_executesql @Query, @ParmDefinition, @ColumnValue= @ColumnValue, @Description = @Description end
声明@Query nvarchar(4000)声明@ Query1 nvarchar(4000)声明@ParmDefinition nvarchar(500);
set @Query = ' insert into tbl_temp(' + quotename(@ColumnName) +',Description) values (@ColumnValue, @Description)' set @Query1 = ' update tbl_temp set' + quotename(@ColumnName) +'=@ColumnValue,
Description=@Description’ set @ParmDefinition = N’@ColumnValue varchar(100),@Description varchar(100)’ if exists(select ‘true’ from tbl_temp where quotename(@ColumnName)=@ColumnValue) begin exec sp_executesql @Query1, @ParmDefinition, @ColumnValue = @ColumnValue, @Description = @Description end else begin exec sp_executesql @Query, @ParmDefinition, @ColumnValue= @ColumnValue, @Description = @Description end
我究竟做错了什么?
这与参数是不可能的。您将需要构建动态查询来实现此目的。
使用动态SQL的proc如下所示:
create procedure MyProc ( @ColumnName varchar(100), @ColumnValue varchar(100), @MH_Description varchar(100) ) as begin declare @Query nvarchar(4000) declare @ParmDefinition nvarchar(500); set @Query = ' insert into Tablename(' + quotename(@ColumnName) +',Description) values (@ColumnValue, @MH_Description)' set @ParmDefinition = N'@ColumnValue varchar(100), @MH_Description varchar(100)' exec sp_executesql @Query, @ParmDefinition, @ColumnValue = @ColumnValue, @MH_Description = @MH_Description end
[编辑]回答第二个问题。使它成为一个查询,而不是两个
set @Query = ' if exists(select * from tbl_temp where '+quotename(@ColumnName)+' = @ColumnValue) update tbl_temp set' + quotename(@ColumnName) +' = @ColumnValue, Description=@Description else insert into tbl_temp(' + quotename(@ColumnName) +',Description) values (@ColumnValue, @Description)'