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:
[EDIT] Answer to your second question. Make it one query instead of two