Continuing my series on how same things can be done differently in SQL Server and MySQL, in this post, we will see how to use dynamic sql
Suppose you want to pass a table name as a parameter and get all rows from it. Create the following table
create table testing(id int, names varchar(100))
insert into testing(id,names)
select 1,'test1' union all
select 2,'test2' union all
select 3,'test3'
SQL Server
declare @table_name varchar(100)
set @table_name='testing'
exec('select * from '+@table_name)
The above code accepts table name as value and select all the rows from it.
MySQL
set @table_name:='testing';
set @sql:=concat('select * from ',@table_name);
prepare st from @sql;
execute st ;
The variable @sql will have the select statement with table name concatenated. The prepare statement prepares the dynamic sql and execute statement executes the statement.
No comments:
Post a Comment