Updating two tables in one SQL query - sql

I'm attempting to update my Scout and ScoutRole tables from one SQL query. I've tried to follow this example: How to update two tables in one statement in SQL Server 2005?.
But I keep receiving the error message
The multi-part identifier "SR.Role" could not be bound
How do I resolve this?
BEGIN TRANSACTION
UPDATE Scout
SET Scout.FirstName = #ScoutFirstName,
Scout.LastName = #ScoutLastName,
Scout.EmailAddress = #EmailAddress,
Scout.ClubID = #ClubID
FROM Scout S, ScoutRole SR
WHERE S.ScoutID = SR.ScoutID AND S.ScoutID = #ScoutID
UPDATE ScoutRole
SET SR.Role = #ScoutRole,
SR.Username = #Username,
SR.Password = #Password
FROM Scout S, ScoutRole SR
WHERE S.ScoutID = SR.ScoutID AND S.ScoutID = #ScoutID
COMMIT

This should be all you need to use:
BEGIN TRANSACTION
UPDATE Scout
SET FirstName = #ScoutFirstName,
LastName = #ScoutLastName,
EmailAddress = #EmailAddress,
ClubID = #ClubID
WHERE ScoutID = #ScoutID
UPDATE ScoutRole
SET Role = #ScoutRole,
Username = #Username,
Password = #Password
WHERE ScoutID = #ScoutID
COMMIT

Related

SQL Stored Procedure Parameter set to Uppercase

I want to force a user's string input in a stored procedure to uppercase. I tried writing UPPER prior to the #parameterName but I got a syntax error. Is this possible? Would be it be better suited to convert the string to uppercase in the statement itself? Here's the code to my SP where I was attempting to use UPPER in the parameter definition.
ALTER PROCEDURE [dbo].[UpdateEntries]
UPPER #ENTRY_TYPE NVARCHAR(20) = '',
UPPER #ENTRY_NAME NVARCHAR(50),
#CLASS_TYPE_ID INT,
#ENTRY_PRICE DEC(4,2),
#ENTRY_DESCRIPT NVARCHAR(max),
#PET_FRIENDLY BIT,
#AGE_RESTRICTION BIT,
#PRICE_RANGE_ID INT,
#RESTAURANT_TYPE_ID INT NULL
AS
BEGIN
SET NOCOUNT ON;
IF #ENTRY_TYPE = 'ACTIVITY'
BEGIN
UPDATE ACTIVITY_DETAIL
SET ACT_NAME = #ENTRY_NAME,
ACT_PRICE = #ENTRY_PRICE,
ACT_DESCRIPT = #ENTRY_DESCRIPT,
ACT_DOG_FRIENDLY = #PET_FRIENDLY,
ACT_AGE_RESTRICTION = #AGE_RESTRICTION,
ACT_PRICE_RANGE_ID = #PRICE_RANGE_ID
WHERE NOT EXISTS (SELECT 1 FROM dbo.[ACTIVITY_DETAIL] WHERE ACT_NAME = #ENTRY_NAME);
END
IF #ENTRY_TYPE = 'BUSINESS'
BEGIN
UPDATE BUSINESS_DETAIL
SET BUSINESS_NAME = #ENTRY_NAME,
BUSINESS_PRICE = #ENTRY_PRICE,
BUSINESS_DESCRIPT = #ENTRY_DESCRIPT,
BUSINESS_DOG_FRIENDLY = #PET_FRIENDLY,
BUSINESS_PRICE_RANGE_ID = #PRICE_RANGE_ID
WHERE NOT EXISTS (SELECT 1 FROM dbo.[BUSINESS_DETAIL] WHERE BUSINESS_NAME = #ENTRY_NAME);
END
IF #ENTRY_TYPE = 'HOTEL'
BEGIN
UPDATE HOTEL_DETAIL
SET HOTEL_NAME = #ENTRY_NAME,
HOTEL_PRICE = #ENTRY_PRICE,
HOTEL_DESCRIPT = #ENTRY_DESCRIPT,
HOTEL_PET_FRIENDLY = #PET_FRIENDLY,
HOTEL_PRICE_RANGE_ID = #PRICE_RANGE_ID
WHERE NOT EXISTS (SELECT 1 FROM dbo.[HOTEL_DETAIL] WHERE HOTEL_NAME = #ENTRY_NAME);
END
IF #ENTRY_TYPE = 'RESTAURANT'
BEGIN
UPDATE RESTAURANT_DETAIL
SET RESTAURANT_NAME = #ENTRY_NAME,
RESTAURANT_PRICE_AVG = #ENTRY_PRICE,
RESTAURANT_DESCRIPT = #ENTRY_DESCRIPT,
RESTAURANT_DOG_FRIENDLY = #PET_FRIENDLY,
RESTAURANT_PRICE_RANGE_ID = #PRICE_RANGE_ID
WHERE NOT EXISTS (SELECT 1 FROM dbo.[RESTAURANT_DETAIL] WHERE RESTAURANT_NAME = #ENTRY_NAME);
END
END
UPPER #ENTRY_TYPE NVARCHAR(20) = '',
UPPER #ENTRY_NAME NVARCHAR(50),
These are wrong. No such usage.
#ENTRY_TYPE NVARCHAR(20) = '',
#ENTRY_NAME NVARCHAR(50),
SELECT #ENTRY_TYPE = UPPER(#ENTRY_TYPE);
SELECT #ENTRY_NAME = UPPER(#ENTITY_NAME);

Code inside SQL Cursor will only execute first FETCH

I have a SQL Cursor which I'm having issues with. When I remove the IF #debug = 1 statement from inside the cursor, only the first record from the FETCH will get updated but if I leave the IF #debug = 1 all the required records are updated. Any idea as to why this is happening, I know most likely something is wrong with my Cursor? Code is below:
DECLARE Verify_Shipment_Cur CURSOR LOCAL FAST_FORWARD READ_ONLY FOR
SELECT DISTINCT lpd_shipment_id, lpd_po_number, lpd_customer_id, lpd_sku, lpd_lottable01, lpd_lottable02, lpd_lottable03, lpd_putaway_zone, lpd_pdt
FROM PO_DETAIL01(NOLOCK)
WHERE lpd_shipment_id = #i_SHIPMENT_ID
AND lpd_po_number = #i_POKEY
AND lpd_customer_id = #i_CUSTOMER_ID
AND lpd_status = #AvailableStatus
OPEN Verify_Shipment_Cur
WHILE #ShipmentSKUCount >= #ShipmentSKUCountCur
BEGIN
FETCH NEXT FROM Verify_Shipment_Cur INTO #ShipmentID, #POKey, #CustomerID, #SKU, #Lottable01, #Lottable02, #Lottable03, #PutawayZone, #PDT
IF EXISTS(SELECT 1 FROM PO_DETAIL(NOLOCK) WHERE pd_asn_number = #i_SHIPMENT_ID AND pd_po_number = #i_POKEY
AND pd_sku = #SKU AND pd_type = #ShmtType AND pd_ordered_qty <> pd_received_qty)
BEGIN
UPDATE PO_DETAIL
SET pd_adjusted_qty = pd_ordered_qty - pd_received_qty
WHERE pd_asn_number = #i_SHIPMENT_ID
AND pd_po_number = #i_POKEY
AND pd_sku = #SKU
AND pd_type = #ShmtType
END
UPDATE PO_DETAIL
SET pd_lottable01 = #Lottable01
, pd_lottable02 = #Lottable02
, pd_lottable03 = #Lottable03
, pd_lottable04 = ''
, pd_lottable05 = #Date
, pd_putaway_zone = #PutawayZone
, pd_pdt = #PDT
, pd_status = #VerifiedStatus
WHERE pd_asn_number = #i_SHIPMENT_ID
AND pd_po_number = #i_POKEY
AND pd_sku = #SKU
AND pd_type = #ShmtType
UPDATE PO_DETAIL01
SET lpd_status = #VerifiedStatus
WHERE lpd_shipment_id = #i_SHIPMENT_ID
AND lpd_po_number = #i_POKEY
AND lpd_customer_id = #i_CUSTOMER_ID
AND lpd_status = #AvailableStatus
IF #debug = 1
BEGIN
SELECT #ShipmentSKUCount AS SKUCOUNT
, #ShipmentSKUCountCur AS SKUCOUNTCUR
, #SKU AS SKU
, #ShipmentID AS SHIPMENT
, #POKey AS POKEY
END
SET #ShipmentSKUCountCur = #ShipmentSKUCountCur + 1
END
CLOSE Verify_Shipment_Cur
DEALLOCATE Verify_Shipment_Cur
It looked ok to me but i obviously dont have your data to assist. Can I recommend putting a few print statements in various parts of your cursor. That way you can see how the code is actually flowing. It doesnt help but thats what I would do.
Please, can you try to define explicilty both variables: set #ShipmentSKUCount=[initial value],set #ShipmentSKUCountCur=[initial or constant value] and see what will happen?
Also, I found there is no checking for a ##FETCH_STATUS. It may also result into reading same row twice or more.
Please, give a feedback.

SQL Server Update Statement

Here is my stored procedure for updating tables in SQL Server, but I can not seem to get it working what is wrong with the statement.
Update pc.PatientCopayId, pc.amount, pc.patientid, pc.apptid ,p.PaymentId,p.PaymentDate,p.PayorType,p.PaymentMethod,
p.RefNumber,p.PaymentAmount,p.PayorId,pt.LastFirstName As PatientName,
ISNULL((SELECT note FROM dbo.PatientNote WHERE NoteTypeId = 28 AND KeyValue = pc.PatientCopayId),'') AS Note
from [dbo].[PatientCopay] pc, dbo.pymt_Payment p, dbo.Patient pt
where ApptId = #ApptId
and p.PaymentId = pc.Paymentid
And pt.PatientId = p.PayorId
Values and meaning
pc.amount, = #PaymentAmount
pc.patientid, = #PatientId
pc.apptid , = #ApptId
p.PaymentId, = #PaymentId
p.PaymentDate, = #PaymentDate
p.PayorType, = #PayorType
p.PaymentMethod, = #PaymentMethod
p.RefNumber, = #RefNumber
p.PaymentAmount, = #PaymentAmount
p.PayorId, = #PayorId
The UPDATE statement shoudl have the following form
UPDATE TableName SET....
Your update statement doesn't have the tablename or the SET keyword.
More Info HERE

execute a stored procedure that returns a " completed succesfully " clue

i have a stored procedure
UPDATE tblTime
SET TimeOut = DATEADD(HOUR,8,TimeIn)
WHERE tId =
(
SELECT MAX(tId)
FROM tblTime
WHERE UserId = 3571
)
although there's no question really, in that case if it did succeed in this query
cause even if the field is empty or if it has value,
it will in this case succeed
but i do need it for future other queries... and also ,
in this case i want the C# code to report
not only that it was requesting query to be execute - meaning it did happen,
but to get an actual answer from sql server
as a return value that c# could use or turn into Boolean
i have managed to do somthing about this so i can specify a condition inside sql server stored proc
declare an OUTPUT variable(PARAMETER) then
set its value to say 1 if condition is met and -1 if not
then
in c# set a function as follows
in this example outpout parameter is named ERROR
public static int UpdateTblViaStoredPRoc(string SPname, int UserID)
{
int message = 0;
using (SqlConnection con = new SqlConnection("server=(local);Initial Catalog=****DBNAME HERE***;Integrated Security=True"))
{
con.Open();
SqlCommand cmd = new SqlCommand(SPname, con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Uid", UserID);
cmd.Parameters.Add("#ERROR", SqlDbType.Int);
cmd.Parameters["#ERROR"].Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
message =(int) cmd.Parameters["#ERROR"].Value;
con.Close();
}
return message;
}
stored proc is then allways following the same pattern
declare ERROR parameter, set a condition to output the ERROR accordingly :
ALTER PROCEDURE [dbo].[nameofProc]
#UId Int, #ERROR int OUT
AS
BEGIN
SET NOCOUNT ON;
DECLARE #TimeOtVal varchar(50)
set #TimeOtVal = (SELECT CASE WHEN [TimeOut] IS NULL THEN '' ELSE CONVERT(NVARCHAR,[TimeOut]) END FROM tblTime WHERE tId = ( SELECT MAX(tId) FROM tblTime WHERE UserId = #UId))
IF (#TimeOtVal = '') -- condition for the update
BEGIN -- now action is taken if condition is met
SET NOCOUNT ON;
UPDATE tblTime SET TimeOut = DATEADD(HOUR,8,TimeIn) WHERE tId = ( SELECT MAX(tId) FROM tblTime WHERE UserId = #UId)
SET #ERROR = 1
END
else
BEGIN -- Other wise , if condition isnot met
SET #ERROR = -1
END
END
so it does what you want only if you allowed it by the condition
then reports the action so you can handle it in program code behind .

sql join problem

Query:
UPDATE EMPLOYEE AS E
INNER JOIN EMPLOYEE_TEL AS T ON E.EMP_NUMBER = T.EMP_NUMBER
SET E.FIRST_NAME = #fname
,E.MID_NAME = #mname
,E.INITIALS =#initilas
,E.SURNAME = #sname
,E.GENDER = #gender
,E.CIVIL_STATUS = #CS
,E.DOB =#datetime
,E.NIC_NUMBER = #nic
,E.ADDRESS_LINE1 =#adline1
,E.ADDRESS_LINE2 = #adline2
,E.ADDRESS_LINE3 = #adline3
,E.EMAIL = #email
,E.DESG_NO =#designo
,E.BASIC_SALARY = #sal
,E.TITLE = #title
,T.TELEPHONE=#tel
WHERE E.EMP_NUMBER=#empnum
I have tried in this SQL Server, but it came up with an error
'Msg 156, Level 15, State 1, Procedure SPUPDATEEMP, Line 21
Incorrect syntax near the keyword 'AS'.
I can't find the error. Is this wrong?
UPDATE EMPLLOYEE
SET FIRST_NAME = #fname
,MID_NAME = #mname
,INITIALS =#initilas
,SURNAME = #sname
,GENDER = #gender
,CIVIL_STATUS = #CS
,DOB =#datetime
,NIC_NUMBER = #nic
,ADDRESS_LINE1 =#adline1
,ADDRESS_LINE2 = #adline2
,ADDRESS_LINE3 = #adline3
,EMAIL = #email
,DESG_NO =#designo
,BASIC_SALARY = #sal
,TITLE = #title
WHERE EMP_NUMBER=#empnum
UPDATE EMPLOYEE_TEL
SET TELEPHONE=#tel
WHERE EMP_NUMBER=#empnum
When doing JOINS you don't need to use "as" to alias a table name.
However, when doing UPDATES you can't alias the name like you are trying to do.
UPDATE E
FROM Employee
What you're trying to do is update two tables at once - you cannot do this in SQL Server - you'll have to split this up into two separate UPDATES:
UPDATE EMPLOYEE
SET
FIRST_NAME = #fname,
MID_NAME = #mname,
.....
TITLE = #title
WHERE
EMP_NUMBER = #empnum
UPDATE EMPLOYEE_TEL
SET
TELEPHONE = #tel
WHERE
EMP_NUMBER = #empnum