Running dynamic query in SQL Server. Exec() and sp_executesql

Both exec() and sp_executesql are used for running dynamic SQL commands, just need to prepare the commands as a String object and call the sp_executesql.
Both of exec() and sp_executesql are same, exec() is the new face of sp_executesql has added in SQL Server V9.

declare @com nvarchar(1024);
set @com='create table MyTable'+convert(varchar(3),@i)+'(id int,[name] varchar(64));';

exec sp_executesql @com;

--exec(@com);--as same as above, the new face

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s