Saturday, February 25, 2012

Creating new table from passed variabe in MSSQL Stored procedure

Hi there i really cant understand why this should be a problem... it seems that i cant create a table from a stored procedure when passing the tablenam from application like this...

CREATE PROCEDURE dbo.CreateTable
@.TableName NVARCHAR(50)
AS
BEGIN

create table @.TableName ([id] int identity(1,1),[diller] int)

end
GO

THIS CANT BE TRUE !!!!!!!!You need to do the following to get it working

CREATE PROCEDURE dbo.CreateTable
@.TableName NVARCHAR(50)
AS

BEGIN
Declare @.SQLStatement nvarchar(4000)

SET @.SQLStatement = 'create table ' + @.TableName + '([id] int identity(1,1),[diller] int)'

Exec (@.SQLStatement )

end
GO

That should do it.

Let me know if you have any questions.|||If it aint to much i would very much like to check for the tables existens before i create it... so basicly i would need to check if the variable exists as a table before i insert it something like

if not exists(Select * From @.TableName)
begin

Stuff...

End

And by the way thk you for the quick reply...|||You can have it as
if not exists(Select * From INFORMATION_SCHEMA.TABLES Where TABLE_NAME = @.TableName)
begin

Stuff...

End

Recently, I wrote article on how to check the objects in database. You can check it at www.aspalliance.com/349 to understand the information_schema views.

Let me know if the above does not work for you.

AP|||Thk you very much been pulling my hair over this... and good article very helpfull... i just startet programming in SQL well my vision is to create websites structured from SQL so that changing stuff around the page is going to be an ease for the user..

thx again...

Jakob

No comments:

Post a Comment