Error creating table in SQL Server with IF - sql-server-2008

I'm getting the following error when trying to create a proc:
Msg 2714, Level 16, State 1, Procedure create_table_test, Line 11
There is already an object named '#tmp' in the database.
The procedure is creating a temp table based on an IF statement but SQL Server doesn't recognize the create table statements are inside an IF and only one will be executed. Any "clean" way around this?
create procedure [dbo].[create_table_test]
AS
BEGIN
set nocount on
if 1=1
create table #tmp (field1 int)
else
create table #tmp (field1 varchar(10))
end

If you're happy to use a global temp table, then you can farm out the creation of the table to two procs. This way the SQL Parser won't get confused.
create procedure [dbo].[create_tmpint]
AS
BEGIN
set nocount on
create table ##tmp (field1 int)
end
go
drop procedure create_tmpvar
go
create procedure [dbo].[create_tmpvar]
AS
BEGIN
set nocount on
create table ##tmp (field1 varchar(10))
end
go
drop procedure create_table_test
go
create procedure [dbo].[create_table_test]
AS
BEGIN
set nocount on
if 1=1 begin
exec [dbo].[create_tmpint]
end
else
exec [dbo].[create_tmpvar]
insert into ##tmp values(1)
select * from ##tmp
end
go
If you run exec [dbo].[create_table_test] you will get the value 1 returned.

You can use this code:
CREATE TABLE #tmp (tempColumn int)
IF 1=1
ALTER TABLE #tmp ADD field1 int
ELSE
ALTER TABLE #tmp ADD field1 varchar(10)
ALTER TABLE #tmp DROP COLUMN tempColumn

Related

Insert into table (select from another table) and some parameters

I want to insert into one table selecting values from another table and some with paramters.
CREATE PROCEDURE `insertuser`(
IN `param1` VARCHAR(50)
)
BEGIN
insert into users(firstname,lastname,email)
select name,nickname,#param1 from members
where id=3;
END
I fill param1 but the query insert null to email
what I need to do?
# symbol is used to define Session variables (accessible to the Session everywhere). You don't need to use # here, as you are using the input parameter value from the Stored procedure.
Try the following instead:
DELIMITER $$
CREATE PROCEDURE `insertuser`(IN `param1` VARCHAR(50))
BEGIN
INSERT INTO users(firstname,lastname,email)
SELECT name,nickname,param1 -- remove # from #param1 here
FROM members
WHERE id=3;
END$$
DELIMITER ;

How do I create a stored procedure that can delete,edit and add a user?

I have three tables:
**friend**-->
Content:user_id,friend_id;
**user**-->
Content:user_id,email,password;
**user_extra**-->
Content:user_id,name,surname,birth_date,country_of_birth,user_name;
And I am suppose to create a stored procedure that can delete, edit and add a user, but I have no clue where to even start. It would be nice if someone helped me or just aim me in the right direction.
Ypu can create a stored procedure based on similar lines as per your requirement and Table Structure.
CREATE PROCEDURE [dbo].[Customers_CRUD]
#Action VARCHAR(10)
AS
BEGIN
SET NOCOUNT ON;
--INSERT
IF #Action = 'INSERT'
BEGIN
INSERT INTO Table
VALUES (a, b)
END
--UPDATE
IF #Action = 'UPDATE'
BEGIN
UPDATE table
SET Name = #Name, Country = #Country
WHERE CustomerId = #CustomerId
END
--DELETE
IF #Action = 'DELETE'
BEGIN
DELETE FROM Table
WHERE CustomerId = #CustomerId
END
END

split string and insert trigger phpMyAdmin

I want to get the name in test table and split it form "to" word & insert that splitted string in abc table.
the trigger fired,but when insert data into test it generate
"#1172 - Result consisted of more than one row" error in phpMyAdmin.
please help me with this.
DROP TRIGGER IF EXISTS `split_after_insert`;
CREATE DEFINER=`root`#`localhost`
TRIGGER `split_after_insert` AFTER INSERT ON `test`
FOR EACH ROW
BEGIN
DECLARE vName varchar(50);
-- Find name of person performing the INSERT into table
SELECT SUBSTR(name,(POSITION("to" IN name)+4),20) FROM test INTO vName;
-- Insert record into abc table
INSERT INTO abc(a) VALUES (vName);
END
DROP TRIGGER IF EXISTS `j`;
CREATE DEFINER=`root`#`localhost`
TRIGGER `j` AFTER INSERT ON `test`
FOR EACH ROW
BEGIN
DECLARE vName varchar(100);
DECLARE vtemp varchar(100);
select new.name into vtemp;
-- Find name of person performing the INSERT into table
SELECT SUBSTR(vtemp,(POSITION("to" IN vtemp)+3),20) INTO vName;
-- Insert record into abc table
INSERT INTO `abc`(`a`) VALUES (vName );
END

Edit a Stored Procedure using ALTER?

I have created a Stored Procedure
CREATE PROCEDURE GetAllRecords()
BEGIN
SELECT * FROM my_table;
END //
Now I want to add a parameter to this Stored Procedure like this :
CREATE PROCEDURE GetAllRecords(id1 INT(4))
BEGIN
SELECT * FROM my_table WHERE `id` = id1;
END //
How can I edit my Stored Procedure?
Delete the procedure
drop procecdure GetAllRecords//
And recreate it
CREATE PROCEDURE GetAllRecords(id1 INT(4)) ...
You have drop procedure first and then re-create it
DROP PROCEDURE IF EXISTS GetAllRecords;
CREATE PROCEDURE GetAllRecords(IN _id INT)
SELECT *
FROM my_table WHEREid = _id;
And since you're using the only statement in your procedure you can ditch BEGIN ... END block and use a usual delimiter.
In case you're wondering no you can not use ALTER PROCEDURE in this case
This statement can be used to change the characteristics of a stored
procedure. However, you cannot change the parameters or body of a
stored procedure using this statement; to make such changes, you
must drop and re-create the procedure using DROP PROCEDURE and CREATE PROCEDURE.
First of all ,This is not how you can pass the parameter in stored procedure.
You can not alter stored procedure, the way to do this is drop existing and create new one.
DELIMITER $$
DROP PROCEDURE IF EXISTS GetAllRecords$$
CREATE PROCEDURE GetAllRecords(IN param1 INT, OUT pram2 Varchar(100), INOUT param3 Date)
BEGIN
select * from <tbl>;
< Your queries>
END$$
DELIMITER ;
For Full detail of stored procedure
please follow the link
http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/
http://dev.mysql.com/tech-resources/articles/mysql-storedprocedures.pdf
To Alter a stored Procedure check this link
http://technet.microsoft.com/en-us/library/ms345356.aspx
The best way is to drop the stored proceure and create it again
DROP PROCEDURE IF EXISTS GetAllRecords
CREATE PROCEDURE GetAllRecords(IN _id INT)
AS
BEGIN
SELECT *
FROM my_table WHEREid = _id;
END

how to works on insert,update data from a table using store Procedure

if i use one table in two different Stored procedure name, (one for insert , one for update command) it showing syntax error.
first i created studentrc SP:
delimiter //
create procedure studentrc(in student_name varchar(20),in Reg_no int(6),in mark1 int(3), in mark2 int(3),in total int(10))
begin
insert into studentrecords values(student_name,Reg_no,mark1,mark2,total);
end; //
no errors
next i create studentrcs SP:
delimiter //
create procedure studentrcs(inout Reg_no int(6))
begin
UPDATE studentrecords
set student_name=?,mark1=?,mark2=?,total=?
where Reg_no=?;
end;//
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UPDATE studentrecords
set student_name=?,mark1=?,mark2=?,total=?
where Reg_no=' at line 3
how can rectify this error...
I'll be the first to admit I'm not a SQL guru by any means, but shouldn't you be taking in more variables and using them in place of the question marks?
You need to put the news values in the args list
create procedure studentrcs(sname varchar(100),m1 varchar(100),m2 varchar(100),total int,inout Reg_noarg int(6))
begin
UPDATE studentrecords
set student_name=sname ,mark1=m1,mark2=m2,total=totalarg
where Reg_no=Reg_noarg ;
for "INSERT"
DELIMITER $$
DROP PROCEDURE IF EXISTS `mydatabase`.`myprocedurename` $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `myprocedurename`(IN field1 VARCHAR(50),
IN field2 INT(10),IN field3 INT(10), IN field4 VARCHAR(10))
BEGIN
INSERT INTO mytablename (FIELD_1,FIELD_2,FIELD_3,FIELD_4) VALUES
(field1,field2,field3,field4);
END $$
DELIMITER ;
size which i have given in IN parameter should be equal to field size in table
for "UPDATE"
DELIMITER $$
DROP PROCEDURE IF EXISTS `mydatabase`.`myprocedurename` $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `myprocedurename`(IN field1 VARCHAR(50),
IN field2 INT(10) )
BEGIN
UPDATE mytablename SET FIELD_1=filed1 WHERE FIELD_2=field2;
END $$
size which i have given in IN parameter should be equal to field size in table
hope this may help you.