I have 6 table with different fields. I want to access table name dynamically. is there any idea to do it? My code is below this is simple procedure which I want to make dynamic
As Robert Harvey mentioned it is a bad idea, anyway if you want to you can do something like....
CREATE PROCEDURE Insert_Data
@TableName SYSNAME
,@Column1 SYSNAME = NULL
,@Column2 SYSNAME = NULL
,@Column3 SYSNAME = NULL
,@Value1 NVARCHAR(100) = NULL
,@Value2 NVARCHAR(100) = NULL
,@Value3 NVARCHAR(100) = NULL
AS
BEGIN
SET NOCOUNT ON;
DECLARE @Sql NVARCHAR(MAX);
SET @Sql = N' INSERT INTO ' + QUOTENAME(@TableName)
+ N' ( '
+ STUFF(
CASE WHEN @Column1 IS NOT NULL
THEN N',' + QUOTENAME(@Column1) ELSE N'' END
+ CASE WHEN @Column2 IS NOT NULL
THEN N',' + QUOTENAME(@Column2) ELSE N'' END
+ CASE WHEN @Column3 IS NOT NULL
THEN N',' + QUOTENAME(@Column3) ELSE N'' END
,1,1,'')
+ N' ) '
+ N' VALUES ( '
+ STUFF(
CASE WHEN @Value1 IS NOT NULL
THEN N', @Value1' ELSE N'' END
+ CASE WHEN @Value2 IS NOT NULL
THEN N', @Value2' ELSE N'' END
+ CASE WHEN @Value3 IS NOT NULL
THEN N', @Value3' ELSE N'' END
,1,1,'')
+ N' ) '
Exec sp_executesql @Sql
,N'@Value1 NVARCHAR(100),@Value2 NVARCHAR(100),@Value3 NVARCHAR(100)'
,@Value1
,@Value2
,@Value3
END