开发者

Column name as a parameter in INSERT statement

开发者 https://www.devze.com 2023-03-14 16:29 出处:网络
I want to create one stored procedure where i want to insert values in a table. But i don\'t know in which field i have to insert values and at the

I want to create one stored procedure where i want to insert values in a table. But i don't know in which field i have to insert values and at the runtime i will decide in which field the values should be inserted. What i want to do is

insert into Tablename(@ColumnName, Description) 
values (@ColumnValue, @MH_Description)

Can it possible that i pass this type of parameters in stored procedure as shown in the example above??

I want to use conditions too as

declare @Query nvarchar(4000) declare @Query1 nvarchar(4000) declare @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

What am I doing wrong?


This is not possible to do with parameters. You will need to build dynamic query to achieve this.

The proc that uses dynamic SQL would look like this:

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

[EDIT] Answer to your second question. Make it one query instead of two

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)'
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号