James James - 5 days ago 6
C# Question

I need to create a sql server database table using visual studio(c# language) . But the name of the table has to be an input from the user

con1.Open();
cmd = new SqlCommand("create table [dbo.][" + textBox2.Text + "](sno int primary key identity(1,1),[Week] [int] not null ,Date nvarchar(30) not null,Time nvarchar(30) not null,Monday_1st_half nvarchar(20),Monday_2nd_half nvarchar(20),Tuesday_1st_half nvarchar(20),Tuesday_2nd_half nvarchar(20),Wednesday_1st_half nvarchar(20),Wednesday_2nd_half nvarchar(20),Thursday_1st_half nvarchar(20),Thursday_2nd_half nvarchar(20),Friday_1st_half nvarchar(20),Friday_2nd_half nvarchar(20),Saturday_1st_half nvarchar(20),Saturday_2nd_half nvarchar(20),Sunday_1st_half nvarchar(20),Sunday_2nd_half nvarchar(20))", con1);
cmd.ExecuteNonQuery();
con1.Close();


This query works if i give the table a hard coded name instead of the textbox.text value, a table is created.
But when i use this code it creates a table with the name 'dbo.'.
If i delete the "[dbo.]" from the query, it gives an error saying 'object is missing'. can someone help me out?.

Answer

Here's a better way to do this. First create the following stored procedure:

CREATE PROC dbo.MakeUserTable(@Tablename as SYSNAME) As

    DECLARE @CleanName As SYSNAME;
    SET @CleanName = QUOTENAME(@Tablename, '[');

    DECLARE @sql As NVARCHAR(MAX);
    SELECT @sql = 'create table [dbo].' + @CleanName + '(sno int primary key identity(1,1),[Week] [int]  not null ,Date nvarchar(30) not null,Time nvarchar(30) not null,Monday_1st_half nvarchar(20),Monday_2nd_half nvarchar(20),Tuesday_1st_half nvarchar(20),Tuesday_2nd_half nvarchar(20),Wednesday_1st_half nvarchar(20),Wednesday_2nd_half nvarchar(20),Thursday_1st_half nvarchar(20),Thursday_2nd_half nvarchar(20),Friday_1st_half nvarchar(20),Friday_2nd_half nvarchar(20),Saturday_1st_half nvarchar(20),Saturday_2nd_half nvarchar(20),Sunday_1st_half nvarchar(20),Sunday_2nd_half nvarchar(20));'

    PRINT 'Executing "'+@sql+'"';
    EXEC(@sql);

Now change your client code to execute this instead, passing in the tablename as a parameter.

I cannot 100% guarantee that this is immune to SQL Injection attacks, but if you have to accept a tablename from a user, this is about as safe as you can get.

Comments