Wednesday, March 28, 2012

Padding partial table name with @variable value

Is there a way to this in SQL
declare @.partial_table_name varchar(128)
set @.partial_table_name = 'mytable'
select * from customer
into tbl_cust_@.partial_table_name
Above i am inserting the values from customer to table
tbl_cust__@.partial_table_name. I want to pass the @.partial_table_name value
to the table so that table name becomes tbl_cust_mytable. This is so that I
can dynamically insert into a table based opon conditions in my store proc.
Any help would be appreciated.
ThanksEXEC('SELECT * INTO tbl_cust_'+@.partial_table_name+' from customer');
I'd be very careful about where @.partial_table_name gets created. SQL
injection can yield to inadvertent statements being executed, such as:
SELECT * INTO tbl_cust_foo FROM (SELECT a=1); UPDATE Employees SET Salary =
Salary * 10 WHERE FullName='Malicious Employee'; SELECT * from customer;
Please give the following article a thorough read:
http://www.sommarskog.se/dynamic_sql.html
"b_dba" <b_dba@.discussions.microsoft.com> wrote in message
news:CB37F1E5-5C85-46B6-B443-6F504E1CD69D@.microsoft.com...
> Is there a way to this in SQL
> declare @.partial_table_name varchar(128)
> set @.partial_table_name = 'mytable'
> select * from customer
> into tbl_cust_@.partial_table_name
> Above i am inserting the values from customer to table
> tbl_cust__@.partial_table_name. I want to pass the @.partial_table_name
> value
> to the table so that table name becomes tbl_cust_mytable. This is so that
> I
> can dynamically insert into a table based opon conditions in my store
> proc.
> Any help would be appreciated.
> Thanks|||Thanks Aaron,
That was very helpful.Its doing what I wanted to do. I would be careful as
where the variable is created.
Appreciate your quick response.
cheers,
b_dba
"Aaron Bertrand [SQL Server MVP]" wrote:

> EXEC('SELECT * INTO tbl_cust_'+@.partial_table_name+' from customer');
> I'd be very careful about where @.partial_table_name gets created. SQL
> injection can yield to inadvertent statements being executed, such as:
> SELECT * INTO tbl_cust_foo FROM (SELECT a=1); UPDATE Employees SET Salary
=
> Salary * 10 WHERE FullName='Malicious Employee'; SELECT * from customer;
> Please give the following article a thorough read:
> http://www.sommarskog.se/dynamic_sql.html
>
>
>
> "b_dba" <b_dba@.discussions.microsoft.com> wrote in message
> news:CB37F1E5-5C85-46B6-B443-6F504E1CD69D@.microsoft.com...
>
>

No comments:

Post a Comment