How to Modify a Value using stored procedure - sql

I'm new to SQL and I'm stuck. If anyone could please help me out.
I have a stored procedure modifyMobileNo to change a mobile number, where ID and MobileNo are the parameters. Change Sarah Furgerson's number to 3246568413
Table columns:
ID INT NOT NULL
FirstName NVARCHAR(20) NOT NULL
LastName NVARCHAR(20) NOT NULL
HouseUnitLotNum NVARCHAR(5) NOT NULL
Street NVARCHAR(50) NOT NULL
Suburb NVARCHAR(50) NOT NULL
State NVARCHAR(3) NOT NULL
PostCode NCHAR(4) NOT NULL
MobileNo NCHAR(10) NULL
DateOfBirth DATE NOT NULL
Gender NCHAR(10) NOT NULL
Ref NVARCHAR(4) NOT NULL
CREATE PROCEDURE modifyMobileNo #ID INT, #MobileNo NCHAR(10)
AS
SELECT ID, Firstname, LastName, MobileNo
FROM Table
WHERE ID = #ID AND MobileNo = #MobilePNo
BEGIN
Do I need to add more parameters? Sorry, so confused.
Not sure where to start.
BEGIN
SET NOCOUNT ON;
UPDATE Table
SET ID = #ID,
MobileNo = #MobileNo
WHERE
FirstName = #FirstName
AND LastName = #LastName
END

seems like it should be something simple like -
CREATE PROCEDURE modifyMobileNo #ID INT, #MobileNo NCHAR(10)
AS
BEGIN
UPDATE Table
SET MobileNo = #MobileNo
WHERE ID = #ID
END

Related

Create a stored procedure for a table named X

CREATE TABLE Persons
(
ID int NOT NULL,
ModifiedDate datetime,
FirstName varchar(50),
LastName varchar(50),
EMail varchar(30),
PhoneNumber varchar(15),
PRIMARY KEY (ID)
);
GetX (int IDX)
if the parameter is null returns all the rows of the table ordered by ModifiedDate field in descending order
otherwise returns just the row that matches the ID
What you are wanting is a "catch all" query. For SQL Server, this can be done a couple of ways. Aaron Bertrand writes about it here.
create procedure GetX (#IDX int = null)
as
select
ID
,ModifiedDate
,FirstName
,LastName
,EMail
,PhoneNumber
from Persons
where #IDX is null or ID = #IDX
order by ModifiedDate desc
Then
exec GetX #IDX = 4;
exec GetX #IDX = null;

Error converting data type varchar to int.?

My table is below
CREATE TABLE Customers
(
CustomerID int identity(1,1) not null primary key,
Name varchar(50) not null,
PhoneNumber varchar(20) not null
constraint chk_PhoneNumber check(PhoneNumber not like '%[^0-9]%'),
DoorNo varchar(50) not null,
StreetName varchar(50) not null,
City varchar(50) not null,
Statee varchar(50) not null,
Zipcode int not null
)
My stored procedure:
ALTER PROCEDURE stp_customers_insert
(#customerid int,
#name varchar(50),
#phone varchar(50),
#doorno varchar(50),
#streetname varchar(50),
#city varchar(50),
#state varchar(50),
#zip int)
AS
BEGIN
IF EXISTS (SELECT CustomerID FROM Customers WHERE CustomerID = #customerid)
BEGIN
RAISERROR ('employee id already exists', 1, 1)
END
ELSE
BEGIN
INSERT INTO Customers (Name, PhoneNumber, DoorNo, StreetName, City, Statee, Zipcode)
VALUES (#name, #phone, #doorno, #streetname, #city, #state, #zip)
END
END
Sample call:
exec stp_customers_insert 'ram', '674673932', '122', '5th cross', 'trichy', 'tamilnadu', 620001
I get this error:
Msg 8114, Level 16, State 5, Procedure stp_customers_insert, Line 23
Error converting data type varchar to int.
The problem appears to be that your stored procedure expects 8 parameters:
stp_customers_insert(#customerid int, #name varchar(50), #phone varchar(50),
#doorno varchar(50), #streetname varchar(50), #city varchar(50),
#state varchar(50), #zip int)
but you are only passing 7 parameters when you actually call the proc:
exec stp_customers_insert 'ram','674673932','122','5th cross','trichy','tamilnadu',620001
If you don't know or don't want to perform the duplicate check on the CustomerID, then you could slightly modify your call to just pass NULL:
exec stp_customers_insert NULL, 'ram','674673932','122','5th cross','trichy','tamilnadu',620001
As an aside, if the proc is not even inserting the CustomerID, and this field is auto increment, then I don't see the point of passing it. Instead, you might want to consider using a unique constraint to achieve the same.
exec stp_customers_insert 1,'ram','674673932','122','5thcross','trichy','tamilnadu',620001
You have to pass #customerid value in procedure parameters - then it will execute without error.
In your table structure CustomerID is defined as INT. But as your stored procedure is defined in this format:
stp_customers_insert(#customerid int,#name ....
You are sending ram as value for customerid in
exec stp_customers_insert 'ram','674673932'....
Correct this to:
exec stp_customers_insert '*enter the CustId value here*','ram','674673932'....
Replace *enter the CustId value here* with the CustomerID
Also change:
insert into Customers(Name,PhoneNumber,DoorNo,StreetName,City,Statee,Zipcode) values(#name,#phone,#doorno,#streetname,#city,#state,#zip)
To include CustomerID as:
insert into Customers(CustomerID,Name,PhoneNumber,DoorNo,StreetName,City,Statee,Zipcode) values(#customerid,#name,#phone,#doorno,#streetname,#city,#state,#zip)
I suggest remove #customerid from sp CustomerID is auto increment field so no need to pass any value for CustomerID. It should be like this:
alter procedure stp_customers_insert(#name varchar(50),#phone varchar(50),#doorno varchar(50),#streetname varchar(50),#city varchar(50),#state varchar(50),#zip int)
as
begin
if exists(select CustomerID from Customers where Name = #name ,phone = #phone ,doorno = #doorno ,streetname = #streetname ,city= #city,state= #state , zip = #zip )
begin
raiserror('employee id already exists',1,1)
end
else
begin
insert into Customers(Name,PhoneNumber,DoorNo,StreetName,City,Statee,Zipcode) values(#name,#phone,#doorno,#streetname,#city,#state,#zip)
end
end
exec stp_customers_insert 'ram','674673932','122','5th cross','trichy','tamilnadu',620001

How to return multiple varchar from a stored procedure where condition is met

Hi I have created a Table in which I am storing first name, last name and email ID of some persons.
The table is as follows:
create table frnds
(
id int Primary Key,
firstName varchar (20) not null,
lastName varchar (20) not null,
emailID varchar (30)not null
)
I have to write a Stored Procedure to return the "first name" values from the table wherever there is a match with the input "last name" value.
I have some of the names with common last names. So I want to have all the first names as the output of the Stored Procedure.
I am using the following code to do that but have been able to get only one matching first name as output.
Create Procedure GetFirstName
(
#lastName varchar(20),
#firstName varchar(20) OUT
)
AS
Begin
Select #firstName = firstName from frnds where lastName = #lastName
End
Also this is how I am displaying the result:
declare #LastName varchar (20)
Exec GetFirstName Daniels, #LastName output
select #LastName
I know that this is because I have the output parameter such that it can hold only one matching first name. Since I am new to SQL, I am not able to figure out how to achieve this. Please help with any suggestion or some link which can guide me in the right direction.
Thanks!!!
You can use temporary table do store the varchars.
First create your procedure like this:
Create table #temp
(
fisrtName varchar(20) not null
)
go
Create Procedure GetFirstName
(
#lastName varchar(20)
-- , #firstName varchar(20) OUT with my solution you don't need it
)
AS
Begin
insert into #temp
Select firstName from frnds where lastName = #lastName
End
go
drop table #temp
Then you can use it as below
Create table #temp
(
fisrtName varchar(20) not null
)
exec GetFirstName 'Daniels'
select * from #temp
Try this
Create Procedure GetFirstName
(
#lastName varchar(20),
#firstName varchar(20) OUT
)
AS
Begin
Select firstName from frnds where lastName = #lastName
End
Create table #lastname(lastname varchar (20))
Insert into #lastname
Exec GetFirstName 'Daniels'
select * from #lastname
CREATE FUNCTION [myschema].[returnLastNames]
(
#lastName varchar(20),
)
RETURNS TABLE
AS
RETURN SELECT firstName from frnds where lastName = #lastName;
A function might be better here maybe?
Use it like f.ex.:
SELECT * FROM myschema.returnLastNames('Stevensson');
IF OBJECT_ID('usp_GetFirstName', 'P') IS NOT NULL
DROP PROCEDURE usp_GetFirstName;
GO
Create Procedure usp_GetFirstName
(
#lastName varchar(20),
#firstName varchar(20) OUTPUT
)
AS
Begin
SET NOCOUNT ON;
Select #firstName = firstName from frnds where lastName = #lastName;
RETURN
End
GO
DECLARE #Person varchar(20);
EXECUTE usp_GetFirstName
N'Daniels',#lastName = #Person OUTPUT;
PRINT 'LAST NAme IS' + #Person;
GO

updating nulls value in sql server

how do i set a column value to null if the user don't select value or set the new value when the user select value
create procedure update2
#SSN int,
#Employee_FirstName varchar(50),
#Employee_lastName varchar(50),
#gender_ID int,
#Department_ID int,
#location_ID int,
#salary decimal(18, 3)
as
Update Employee set Employee_FirstName= #Employee_FirstName,
Employee_lastName=#Employee_lastName,gender=#gender_ID,Department_ID = #Department_ID,
location_ID=#location_ID or location_ID is null , salary=#salary
where SSN = #SSN
You can declare #location_ID as null
CREATE PROCEDURE update2
#SSN INT ,
#Employee_FirstName VARCHAR(50) ,
#Employee_lastName VARCHAR(50) ,
#gender_ID INT ,
#Department_ID INT ,
#location_ID INT = NULL ,
#salary DECIMAL(18, 3)
AS
UPDATE Employee
SET Employee_FirstName = #Employee_FirstName ,
Employee_lastName = #Employee_lastName ,
gender = #gender_ID ,
Department_ID = #Department_ID ,
location_ID = #location_ID ,
salary = #salary
WHERE SSN = #SSN
Try this one, If I correctly understood your question -
CREATE PROCEDURE dbo.update2
#SSN INT,
#Employee_FirstName VARCHAR(50),
#Employee_lastName VARCHAR(50),
#gender_ID INT,
#Department_ID INT,
#location_ID INT,
#salary DECIMAL(18, 3)
AS BEGIN
UPDATE dbo.Employee
SET
Employee_FirstName = #Employee_FirstName
, Employee_lastName = #Employee_lastName
, gender = #gender_ID
, Department_ID = #Department_ID
, location_ID = ISNULL(location_ID, #location_ID) --<-- ??
, salary = #salary
WHERE SSN = #SSN
END
#location_ID INT = NULL -- specify NULL like this wherever you need
But you have to remove any relations(foreign key) with this particular column otherwise you will get conflict occur error at the time of updation
Thanks
Arun Antony

SQL problem: same column in one

hy!
I have 2 tables and in each I have a column date, I need to make a single table with the information from all 2 tables with a column date which i want to get from the 3 tables,but in the same column
i tried the following code, but didn`t work
CREATE FUNCTION dbo.GetContactInformation(#id int)
RETURNS #retActivityInformation TABLE
(
ClientID int NOT NULL,
ActivityDate datetime NULL,
Tipe nvarchar(50) NULL,
Number nvarchar(50) NULL,
Value int NULL,
Statu nvarchar(50) NULL,
PRIMARY KEY CLUSTERED (clientID ASC)
) AS
BEGIN
DECLARE
#ClientID int,
#ActivityDate datetime,
#Tip nvarchar(50),
#Number nvarchar(50),
#Value int,
#Statu nvarchar(50);
SELECT
#ClientID = ClientID,
#ActivityDate = ActivityDate,
#Number = Number,
#Value = Value,
#Statu = Statu
FROM Fa,Pay
WHERE ID = #id;
SET #ActivityDate =
CASE
WHEN EXISTS(SELECT Fa.DataEmitere FROM Fa AS e
WHERE e.ID = #id)
THEN 'Fa'
WHEN EXISTS(SELECT Pay.Data FROM Pay AS bec
WHERE bec.ID = #id)
THEN 'Pay'
END;
IF #id IS NOT NULL
BEGIN
INSERT #retActivityInformation
SELECT #clientID, #ActivityDate, #Number, #Value,#Statu;
END;
RETURN;
END;
Just prefix the field with the database name. I am going to assume the date you actually mean is ActivityDate. If you want to SELECT/INSERT using this field you will need to prefix with Fa or Pay so it would be Fa.ActivityDate or Pay.ActivityDate.
If this is not the field then we'd need more info.
Use the column by specifying the table name as below:-
CREATE FUNCTION dbo.GetContactInformation(#id int)
RETURNS #retActivityInformation TABLE
(
ClientID int NOT NULL,
ActivityDate datetime NULL,
Tipe nvarchar(50) NULL,
Number nvarchar(50) NULL,
Value int NULL,
Statu nvarchar(50) NULL,
PRIMARY KEY CLUSTERED (clientID ASC)
) AS
BEGIN
DECLARE
#ClientID int,
#ActivityDate datetime,
#Tip nvarchar(50),
#Number nvarchar(50),
#Value int,
#Statu nvarchar(50);
SELECT
#ClientID = ClientID,
#ActivityDate = Fa.ActivityDate,
#Number = Number,
#Value = Value,
#Statu = Statu
FROM Fa,Pay
WHERE ID = #id;
SET #ActivityDate =
CASE
WHEN EXISTS(SELECT Fa.DataEmitere FROM Fa AS e
WHERE e.ID = #id)
THEN 'Fa'
WHEN EXISTS(SELECT Pay.Data FROM Pay AS bec
WHERE bec.ID = #id)
THEN 'Pay'
END;
IF #id IS NOT NULL
BEGIN
INSERT #retActivityInformation
SELECT #clientID, #ActivityDate, #Number, #Value,#Statu;
END;
RETURN;
END;
See the middle part here:
CREATE FUNCTION dbo.GetContactInformation(#id int)
RETURNS #retActivityInformation TABLE
(
ClientID int NOT NULL,
ActivityDate datetime NULL,
Tipe nvarchar(50) NULL,
Number nvarchar(50) NULL,
Value int NULL,
Statu nvarchar(50) NULL,
PRIMARY KEY CLUSTERED (clientID ASC)
) AS
BEGIN
DECLARE
#ClientID int,
#ActivityDate datetime,
#Tip nvarchar(50),
#Number nvarchar(50),
#Value int,
#Statu nvarchar(50);
SELECT
#ClientID = ClientID,
#ActivityDate = ActivityDate,
#Number = Number,
#Value = Value,
#Statu = Statu
FROM Fa,Pay
WHERE ID = #id;
SET #ActivityDate = ISNULL(
(SELECT top 1 Fa.DataEmitere FROM Fa AS e WHERE e.ID = #id),
(SELECT top 1 Pay.Data FROM Pay AS bec WHERE bec.ID = #id))
IF #id IS NOT NULL
BEGIN
INSERT #retActivityInformation
SELECT #clientID, #ActivityDate, #Number, #Value,#Statu;
END;
RETURN;
END;
Essentially, instead of testing to see if the data EXISTS just to get the field name, get the data directly.