Insert into Table Variable getting Column name or number of supplied values does not match table definition - sql-server-2008

DECLARE #myTemp TABLE (Item Varchar(10) Not Null,
[Description Varchar(30) Not Null,
LonDescription Varchar(50),
[Level] Char(1),
LevelDesc Varchar(15),
GID Varchar(16),
[Min] Int,
[Max] Int,
QTY Int,
QoO Int)
FETCH NEXT FROM cAreaLocationItems Into #citem,#cDesc,#cLDesc,#cLVL,#cLVLDesc,#cGID,#cMin,#cMax,#cqty
IF ##FETCH_STATUS <> 0 -- We're out of items
BREAK
WHILE ##FETCH_STATUS = 0
Begin
Declare #QoO Int
SELECT #QoO = SUM(QtyReqd - QtyActual)
FROM abc.tblorders
WHERE (ItemNumber = #cItem) AND (Status <> '4') And
Bin = #Location
GROUP BY ItemNumber, UPC, [Level], Description, Bin
If #QoO = Null
Set #QoO = 0
Insert into #myTemp values(#cItem,#cDesc,#cLDesc,#clvl,#cLVLDesc,#cGid,#cMin,#cMax,#cQTy,#QoO)
FETCH NEXT FROM cAreaLocationItems Into #citem,#cDesc,#cLDesc,#cLVL,#cLVLDesc,#cGID,#cMin,#cMax,#cqty
end
Get the error executed stored procedure on the insert into #myTemp table variable defined above. Table says 10 columns and insert has ten values. Any help?

Try to specify the column names in the insert query like this:
Insert into #myTemp (Item Varchar,[Description,LonDescription,Level],LevelDesc,GID,[Min],[Max],QTY,QoO) values(#cItem,#cDesc,#cLDesc,#clvl,#cLVLDesc,#cGid,#cMin,#cMax,#cQTy,#QoO)
It helps you to avoid error when you add new column into the table

Related

SQL - Procedure function

Trying to create a Procedure to (Insert, Delete and, Update) values in employee_details.
CREATE DEFINER=`root`#`localhost` ALTER PROCEDURE `alter_employeedetails`(in employee_id int(11), employee_name VARCHAR(30), employee_join_date date,
employee_desgination varchar(30), employee_salary bigint(20), employee_address varchar(30),
employee_contact varchar(30), employee_email_id varchar(30)
BEGIN
IF #StatementType = 'Insert'
BEGIN
insert into employee_details values
(employee_id, employee_name, employee_join_date, employee_desgination, employee_salary, employee_address, employee_contact, employee_email_id)
END
IF #StatementType = 'Update'
BEGIN
UPDATE employee_details SET
(employee_name = #employee_name, employee_join_date = #employee_join_date, employee_designation = #employee_desgination,
employee_salary = #employee_salary, employee_address = #employee_address, employee_contact = #employee_contact, employee_email_id = #employee_email_id)
WHERE employee_id = #employee_id
END
else IF #StatementType = 'Delete'
BEGIN
DELETE FROM employee_details where employee_id = #employee_id
END
end
Quite a few errors in that code...
You forgot to prefix all the parameters with the "#" symbol.
Forgot to include "#StatementType" as a parameter.
Update had brackets around it.
You cannot specify int(11) (employee_id) or bigint(20)
(salary). It's either int / bigint (you don't specify the length
for int/bigint datatypes). And is salary correct as bigint? MSSQL has a "money"
datatype, or you could use decimal(8,2) or something similar. You
might be multiplying the salary by 100 to shift the decimal place for
all I know?
When inserting, do you really want to insert a employee Id? This would normally be an auto-incrementing primary key
Insert statement missing the fields you were populating. Required if using the "values" keyword like you had specified.
Hopefully this is closer to what you want.
ALTER PROCEDURE alter_employeedetails
(#StatementType as varchar(25), #employee_id int, #employee_name VARCHAR(30), #employee_join_date date,
#employee_designation varchar(30), #employee_salary bigint, #employee_address varchar(30),
#employee_contact varchar(30), #employee_email_id varchar(30))
AS
BEGIN
IF #StatementType = 'Insert'
BEGIN
insert into employee_details
(employee_id, employee_name, employee_join_date, employee_designation, employee_salary, employee_address, employee_contact, employee_email_id)
values
(#employee_id, #employee_name, #employee_join_date, #employee_designation, #employee_salary, #employee_address, #employee_contact, #employee_email_id)
END
ELSE IF #StatementType = 'Update'
BEGIN
UPDATE employee_details
SET
employee_name = #employee_name,
employee_join_date = #employee_join_date,
employee_designation = #employee_designation,
employee_salary = #employee_salary,
employee_address = #employee_address,
employee_contact = #employee_contact,
employee_email_id = #employee_email_id
WHERE employee_id = #employee_id
END
ELSE IF #StatementType = 'Delete'
BEGIN
DELETE FROM employee_details where employee_id = #employee_id
END
END

i want to insert same record for status=0 for the below code in mysql. but my logic is not working.can any one suggest me

I want to insert same record for status=0. But my logic is not working in MySQL.
Please add more text over here...
This question is about a stored procedure. And the user didn't provide any info what so ever.
CREATE DEFINER=`root`#`localhost` PROCEDURE `sp_insert2`(
IN P_page_Id int(11) ,
IN P_LanguageCode char,
IN P_page_status int(11),
IN p_created_by int(11),
IN p_created_date datetime,
OUT P_return int)
BEGIN
DECLARE v_isRecordExisting int;
DECLARE v_flags int;
SELECT
COUNT(*)
INTO
v_isRecordExisting
FROM
tbl_cms_pages_languages2
WHERE
page_status in(0,1)
AND
page_id = p_page_Id
AND
languagecode = P_LanguageCode;
IF
v_isRecordExisting = 0
THEN
INSERT INTO tbl_cms_pages_languages2 (
page_Id,
LanguageCode,
page_status,
created_by,
created_date
)
VALUES(
P_page_Id,
P_LanguageCode,
P_page_status,
P_created_by,
p_created_date
);
SET
p_return = 0;
ELSE
SET
p_return = 2;
END IF;
END

mysql stored procedure checking if record exists

I created the following stored procedure:
CREATE DEFINER=`root`#`localhost` PROCEDURE `add_summit`(IN `assoc_code` CHAR(5), IN `assoc_name` CHAR(50), IN `reg_code` CHAR(2), IN `reg_name` CHAR(100), IN `code` CHAR(20), IN `name` CHAR(100), IN `sota_id` CHAR(5), IN `altitude_m` SMALLINT(5), IN `altitude_ft` SMALLINT(5), IN `longitude` DECIMAL(10,4), IN `latitude` DECIMAL(10,4), IN `points` TINYINT(3), IN `bonus_points` TINYINT(3), IN `valid_from` DATE, IN `valid_to` DATE)
BEGIN
declare assoc_id SMALLINT(5);
declare region_id SMALLINT(5);
declare summit_id MEDIUMINT(8);
-- ASSOCIATION check if an association with the given code and name already exists
SELECT id INTO assoc_id FROM association WHERE code = assoc_code LIMIT 1;
IF (assoc_id IS NULL) THEN
INSERT INTO association(code, name) VALUES (assoc_code, assoc_name);
set assoc_id = (select last_insert_id());
END IF;
-- REGION check if a region with the given code and name already exists
SET region_id = (SELECT id FROM region WHERE code = reg_code AND name = reg_name AND association_id = assoc_id);
IF (region_id IS NULL) THEN
INSERT INTO region(association_id, code, name) VALUES (assoc_id, reg_code, reg_name);
set region_id = (select last_insert_id());
END IF;
-- SUMMIT check if a summit with given parameters already exists
SET summit_id = (SELECT id FROM summit WHERE association_id = assoc_id AND region_id = region_id);
IF (summit_id IS NULL) THEN
INSERT INTO summit(code, name, sota_id, association_id, region_id, altitude_m, altitude_ft, longitude,
latitude, points, bonus_points, valid_from, valid_to)
VALUES (code, name, sota_id, assoc_id, region_id, altitude_m, altitude_ft, longitude, latitude,
points, bonus_points, valid_from, valid_to);
END IF;
END$$
basically, it should check if a record exists in some tables and, if it doesn't, it should insert it and use the inserted id (auto increment).
The problem is that even if the record exists (for instance in the association table), assoc_id keeps returning null and that leads to record duplication.
I'm new to stored procedures so I may be doing some stupid errors. I've been trying to debug this SP for hours but I cannot find the problem.
A newbie mistake.
I forgot to specify the table name in the field comparison and that leads to some conflicts with param names (for example the param name).
A good idea is to specify some kind of prefix for parameters (like p_) and always specify the name of the table in the SP.

Stored procedure for Inserting Data into 3 tables. Not working.

I have 3 tables-
1. Country (CountryName, CID (PK- AutoIncrement))
2. State (SID(PK- AutoIncrement), StateName, CID (FK to Country)
3. City (CityName, CID, SID (FK to State)
Now I need to insert only the name into the three tables with CountryName, StateName and CityName.. The IDs need to get updated.
Create PROCEDURE sp_place(
#CountryName char(50),
#StateName varchar(50),
#CityName nchar(20)
)
AS
DECLARE #CountryID int, #StateID int, #CityID int;
Set NOCOUNT OFF
BEGIN TRANSACTION
INSERT INTO dbo.Country VALUES (#CountryName);
SET #CountryID = SCOPE_IDENTITY();
IF ##ERROR <> 0
BEGIN
ROLLBACK
RETURN
END
Insert into dbo.State VALUES (#StateName, #CountryID);
SET #StateID = SCOPE_IDENTITY();
IF ##ERROR <> 0
BEGIN
ROLLBACK
RETURN
END
Insert into dbo.City VALUES (#CityName, #StateID);
SET #CityID= SCOPE_IDENTITY();
Commit
When I Enter Country twice, the value shouldn't get changed.
Eg: If I enter India the value of CountryID=1, when I again enter India, the value of CountryID shouldn't get increased.
How'd I perform that? My SP changes for every insertion.
You can check if the country already exist and retrieve the countryID
IF NOT EXISTS(Select 1 FROM Country Where CountryName=#Country)
BEGIN
INSERT INTO dbo.Country VALUES (#CountryName);
SET #CountryID = SCOPE_IDENTITY();
END
ELSE
Select #CountryID = CountryID From Country Where CountryName=#Country
You can do the same for State and City if required
Hello try with this syntax
IF EXISTS (SELECT * FROM Country WHERE CountryName= #CountryName)
BEGIN
UPDATE dbo.Country
SET CountryName = #CountryName
WHERE CountryId = (SELECT CountryId FROM dbo.Country WHERE CountryName= #CountryName);
END
ELSE
BEGIN
INSERT INTO dbo.Country(CountryName) VALUES (#CountryName);
END
-- For the identity you must just add identity to your column in your creation script
Why dont you set Unique Constraint on CountryName column that won't allow you to insert duplicate countries at all
You need the MERGE syntax
http://technet.microsoft.com/en-us/library/bb510625.aspx
or to check manually (ie: with IF EXISTS (...) ) for the existence of the country before inserting.

serialising rows in a table

I have a table which contains header information for transactions. The transactions belong to different projects.
In the header I have columns:
rhguid - uniqueidentifier
rhserial - int
rh_projectID - int
First I insert the row (there's more columns)
Then I calculate the serial number for that project:
update responseheader
set rhSerial = 1 + (select isnull(max(rhSerial), 0)
from responseheader
where (rhstatus = 0) AND (rh_projectID = 1234))
where
(rhGUID = <preassignedGUID>);
However when there are many transactions happening at the same time for a project I am finding duplicate rhserial values.
I'm doing this in classic ASP with SQL Server 2008.
Is there a better way?
From your example, it doesn't look like you're using a transaction. My guess is that the SELECT portion of the statement is running as READ UNCOMMITTED, otherwise you would not see duplicates. There are ways to start transactions with ADO, but I prefer using stored procedures instead.
Try implementing something like this:
CREATE PROC dbo.ResponseHeader_Insert
<more data to insert>,
#ProjectID INT,
#Status SMALLINT
as
insert responseheader (column names here)
select <param values here>, isnull(max(rhSerial), 0) + 1
from responseheader
where (rhstatus = #Status) AND (rh_projectID = #ProjectID))
If this doesn't work for ya, try creating sequence tables (one for each sequence).
create table <tablename> (
SeqID int identity(1,1) primary key,
SeqVal varchar(1)
)
Create a procedure to get the next identity:
create procedure GetNewSeqVal_<tablename>
as
begin
declare #NewSeqValue int
set NOCOUNT ON
insert into <tablename> (SeqVal) values ('a')
set #NewSeqValue = scope_identity()
delete from <tablename> WITH (READPAST)
return #NewSeqValue
end
If there are too many sequence tables that need to be created or you want to create sequences on the fly, try this approach:
Create table AllSequences (
SeqName nvarchar(255) primary key, -- name of the sequence
Seed int not null default(1), -- seed value
Incr int not null default(1), -- incremental
Currval int
)
Go
create procedure usp_CreateNewSeq
#SeqName nvarchar(255),
#seed int = 0,
#incr int = 1
as
begin
declare #currval int
if exists (
select 1 from AllSequences
where SeqName = #SeqName )
begin
print 'Sequence already exists.'
return 1
end
if #seed is null set #seed = 1
if #incr is null set #incr = 1
set #currval = #seed
insert into AllSequences (SeqName, Seed, Incr, CurrVal)
values (#SeqName, #Seed, #Incr, #CurrVal)
end
go
create procedure usp_GetNewSeqVal
#SeqName nvarchar(255)
as
begin
declare #NewSeqVal int
set NOCOUNT ON
update AllSequences
set #NewSeqVal = CurrVal = CurrVal+Incr
where SeqName = #SeqName
if ##rowcount = 0 begin
print 'Sequence does not exist'
return
end
return #NewSeqVal
end
go