Reputation: 3629
How can I use a dynamic table name in the below SQL query?
"INSERT INTO `tableName` (`ADUC`, `DHCP`, `DISK`, `DNS`, `Exchange`, `HOSTNAME`, `HWID`, `IP`, `OS`) values (@aduc,@dhcp,@disk,@dns,@exchange,@hostname,@hwid,@ip,@os)"
Currently I am declaring tableName
via
Dim tableName = My.Computer.Name.ToString
I want the table name to reflect the computers name as that's what I've created within PhpMyAdmin, so any thoughs on how to do this?
Please note: that the ``
needs to stay either side of the table name to support hyphenated table names in the query.
Upvotes: 0
Views: 99
Reputation: 1549
You can create store procedure like below and pass tablename and values as parameter because you already know the table schema.
create table dynamictest
create table dynamictest(id varchar(max));
Now you need to insert value but table name is dynamic so you need to pass it.
create PROCEDURE [dbo].[mssql_DynamicTableTest]
@LogTable VARCHAR(1024),
@code NVARCHAR(Max)
AS
BEGIN
DECLARE
@sql NVARCHAR(MAX),
@params NVARCHAR(Max);
SET @params = N'@LogTable VARCHAR(1024),@code NVARCHAR(Max)';
SET @sql = N'INSERT INTO '+@LogTable+' VALUES ('''+@code+''')';
select @sql;
EXEC sp_executesql @sql, @params, @LogTable,@code;
END
Now execute able store procedure by passing table name "dynamictest" and value "test".
Upvotes: 0
Reputation: 28751
"INSERT INTO `"+tableName+"` (`ADUC`, `DHCP`, `DISK`, `DNS`, `Exchange`, `HOSTNAME`, `HWID`, `IP`, `OS`) values (@aduc,@dhcp,@disk,@dns,@exchange,@hostname,@hwid,@ip,@os)"
Upvotes: 2