August 27, 2012

Dynamic SQL - SQL Server Vs MySQL‏




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.

result


Did you like this post?
kick it on DotNetKicks.com
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Madhivanan,an MSc computer Science graduate from Chennai-India, works as a works as a Lead Subject Matter Expert at a company that simplifies BIG data. He started his career as a developer working with Visual Basic 6.0, SQL Server 2000 and Crystal Report 8. As years went by, he started working more on writing queries in SQL Server. He now has good level of knowledge in SQLServer, Oracle, MySQL and PostgreSQL as well. He is also one of the leading posters at www.sqlteam.com and a moderator at www.sql-server-performance.com. His T-sql blog is at http://beyondrelational.com/blogs/madhivanan

 
  Feedback:

comments

0 Responses to "Dynamic SQL - SQL Server Vs MySQL‏"
 

Copyright © 2009-2014 All Rights Reserved for SQLServerCurry.com by Suprotim Agarwal | Terms and Conditions