SQL stored procedure Assistance - stored-procedures

I am trying to accomplish:
A stored procedure that accepts at least one parameter and updates one or more records based on the value passed in the parameter. Two update commands made as part of the same transaction. An error handler that executes if there is an error with a transaction.
With this stored procedure:
DROP PROCEDURE uspPatByState;
GO
CREATE PROCEDURE uspPatByState
(#St varchar (2), #state varchar (2) OUTPUT)
AS
BEGIN
SELECT *
FROM PATIENTS
WHERE STATE = #St;
IF #St IS NOT NULL
SET #St = #state;
UPDATE PATIENTS
SET City = 'Los Angeles'
WHERE City = 'Honolulu'
UPDATE PATIENTS
SET ZipCode = '96801'
WHERE ZipCode = '55555'
SELECT *
FROM PATIENTS
WHERE STATE = #state
RETURN
END
GO
EXEC uspPatByState #St = 'CA' , #state= 'HI'
But it's not working. I am getting:
Address1 Address2 City State ZipCode
1831 Universal Ave NULL Los Angeles CA 55555
1831 Universal Ave NULL Los Angeles CA 55555
What I need to see is:
Address1 Address2 City State ZipCode
1831 Universal Ave NULL Honolulu HI 96801
1831 Universal Ave NULL Honolulu HI 96801

I don't quite understand what kind of logic you want, or what you want to do. But here is how I would use transactions and error handling:
USE mydb;
DROP PROCEDURE uspPatByState;
GO
CREATE PROCEDURE uspPatByState
(#St varchar (2), #state varchar (2) OUTPUT)
AS
BEGIN
BEGIN TRY
BEGIN TRANSACTION
IF(SELECT COUNT(*) FROM PATIENTS WHERE [state] = #st)
BEGIN
UPDATE PATIENTS
SET City = 'Los Angeles'
WHERE City = 'Honolulu'
UPDATE PATIENTS
SET ZipCode = '96801'
WHERE ZipCode = '55555'
END ELSE
BEGIN
SET #state = #st
END
SELECT * FROM PATIENTS WHERE STATE = #st
COMMIT TRANSACTION;
END TRY
BEGIN CATCH
ROLLBACK TRANSACTION;
SELECT ERROR_MESSAGE() AS ErrorMessage;
END CATCH;
RETURN
END
GO
EXEC uspPatByState #St = 'CA' , #state= 'HI'

Related

Error: Query execution failed for dataset. Is my query correct for my dataset SSRS?

I'm trying to use SET,IF,ALTER TABLE. When i run the report it gives me a error 'Query execution failed for dataset'.
This is the query for the dataset:
declare #DOB date
declare #NO VARCHAR (30)
declare #ID VARCHAR(30)
set #DOB = #DOB
set #NO = #NO
set #ID =#ID
IF #DOB is null
begin
SELECT DISTINCT [Name]
into tempName
FROM [Patient]
where [No_]= #NO
or[Id No_] = #ID
END
else
IF #DH is null
begin
SELECT DISTINCT [Name]
into tempName
FROM [Patient]
where DATEOFBIRTH = #DOB
or [Id No_] = #ID
END
else
IF #ID is null
begin
SELECT DISTINCT [Name]
into tempName
FROM [Patient]
where [No_] = #NO
or DATEOFBIRTH = #DOB
end
ALTER TABLE tempName alter column Name varchar (30) NULL
INSERT INTO tempName (Name) values ('Nothing')
SELECT case Name
when '' then ''
when 'Nothing' then '*Nothing'
else Name
end Name
from tempName
order by [Name]
drop table tempName
Can someone help?
table "tempname" is an actual table or it's a temporary table? In the latter case you need to call it with #temptable

Best way to handle Uniquery and identity autoincrement cloumn of a postgresql Table

I get this error: field "bankid" must have a value.
For solving this I must add the field using Uniquery Fields editor and set "required" property to False, also autogeneratedvalue to arAutoInc .
Is it the only way doing this?adding fields to Uniquery?
Table:
CREATE TABLE public.banks (
bank varchar(50),
branch varchar(80),
"no" varchar(30),
bankid integer NOT NULL GENERATED ALWAYS AS IDENTITY,
)
WITH (
OIDS = FALSE
);
uniquery component:
object UniQuery2: TUniQuery
SQLInsert.Strings = (
'INSERT INTO "Banks"'
' (bank, branch, no)'
'VALUES'
' (:bank, :branch, :no) RETURNING bankid;')
SQLUpdate.Strings = (
'update "Banks" set bank=:bank, branch=:branch, "no"=:no'
'where bankid=:bankid')
SQLLock.Strings = (
'')
SQLRefresh.Strings = (
'SELECT bank, branch, no, bankid FROM "Banks"'
'WHERE'
' bankid = :bankid')
SQLRecCount.Strings = (
'SELECT count(*) FROM ('
'SELECT * FROM "Banks"'
''
') t')
Connection = UniConnection1
SQL.Strings = (
'select * from "Banks" order by bank,branch,"no"')
Options.ReturnParams = True
Left = 64
Top = 80
object UniQuery2bank: TStringField
FieldName = 'bank'
Required = True
Size = 50
end
object UniQuery2branch: TStringField
FieldName = 'branch'
Required = True
Size = 80
end
object UniQuery2no: TStringField
FieldName = 'no'
Required = True
Size = 30
end
object UniQuery2bankid: TIntegerField
AutoGenerateValue = arAutoInc
FieldName = 'bankid'
end
end
delphi code:
UniQuery2.Options.DefaultValues := True;
uniquery2.open;
UniQuery2.Append;
UniQuery2.fieldByName('bank').AsString:=sEdit1.Text;
UniQuery2.fieldByName('branch').AsString:=sEdit2.Text;
UniQuery2.fieldByName('no').AsString:=sEdit2.Text;
UniQuery2.Post;
delphi 10.2.3
postgresql 10.8
parameterized form of Ago's solution could solve the problem when Uniquery is not attached to a data source and Dbgrid
uq.sql.text:='upadte table1 set field1=:f';
uq.parambyname('f').asinteger:=somevalue;
uq.execute;
when uniquery has merged data and calculated fields for using with dbgrid :
uq.append;
uq.fieldbyname('field1').asinteger:=somevalue;
//****
uq.filedbyname('id').required:=false;
//****
uq.post;

sql server stored proc returns only one row

I have an issue where only the last record in a csv file is written to the database by my stored procedure. I thought this might be related to the type of file (csv or text) because I have a comma delimited text file with only five records that will write all records, but when I used a csv file only the last record is written. I did read a post which said that this could be related to using a scalar variable in the stored proc but I don't think that this is right because when I use the text file it's still the same stored proc. Please advise.
Thanks!
here's the stored proc:
USE [SomeDB]
GO
/****** Object: StoredProcedure [dbo].[SaveUser] Script Date: 8/1/2016 9:25:24 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
Alter PROCEDURE [dbo].[SaveUser]
-- Add the parameters for the stored procedure here
#PartnerID INT,
#SourceID INT,
#OrgSourcedIDs NVARCHAR(50),
#Role NVARCHAR(50),
#UserID NVARCHAR(50),
#GivenName NVARCHAR(50),
#FamilyName NVARCHAR(50),
#Email NVARCHAR(50),
#Grade NVARCHAR(50),
#Identifier NVARCHAR(50)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #ReturnVal NVARCHAR(10)
DECLARE #IsTransfer Bit = 0
DECLARE #IsUpdate BIT = 0
SELECT #IsTransfer = CASE WHEN OrgSourcedIDs != #OrgSourcedIDs THEN 1 ELSE 0 END,
#IsUpdate = CASE WHEN HASHBYTES('SHA', GivenName +FamilyName +Email +Grade ) != HASHBYTES('SHA', #GivenName + #FamilyName + #Email + #Grade ) THEN 1 ELSE 0 END
FROM dbo.tblUsers a
WHERE a.PartnerID = #PartnerID AND a.SourcedID = #SourceID
IF ##RowCount = 0
BEGIN
-- If not, add it to staging table with ACTION = INSERT (into tblUser)
INSERT INTO dbo.tblUsers
( PartnerID, SourcedID, OrgSourcedIDs, Role, UserID,
GivenName, FamilyName, Email, Grade, Identifier,
Action )
VALUES
( #PartnerID, #SourceID, #OrgSourcedIDs, #Role, #UserID,
#GivenName, #FamilyName, #Email, #Grade, #Identifier,
'Create' )
--SELECT #ReturnVal = 'INSERT'
END
ELSE IF (#IsTransfer = 1)
BEGIN
UPDATE dbo.tblUsers
SET
OrgSourcedIDs = #OrgSourcedIDs,
UserID = #UserID,
GivenName = #GivenName,
FamilyName = #FamilyName,
Email = #Email,
Grade = #Grade,
Identifier = #Identifier,
Action = 'Transfer'
WHERE
PartnerID = #PartnerID
AND SourcedID = #SourceID
END
ELSE IF(#IsUpdate = 1)
BEGIN
UPDATE dbo.tblUsers
SET
UserID = #UserID,
GivenName = #GivenName,
FamilyName = #FamilyName,
Email = #Email,
Grade = #Grade,
Identifier = #Identifier,
Action = 'Update'
WHERE
PartnerID = #PartnerID
AND SourcedID = #SourceID
END
--SELECT #ReturnVal
END
GO

Multiple condition WHERE clause returning unnecessary rows

In the stored procedure below, I'm wanting to return rows that do not have DEL in the Flag column. When I get the result back, the DEL rows are included. What am I doing wrong in my WHERE clause(I'm assuming that's what it is)?
ALTER PROCEDURE [dbo].[GetAllMessages]
-- Add the parameters for the stored procedure here
#Key varchar(30)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
SELECT message.msg_id,
message.tenant_id,
message.sender_id,
message.recipient_id,
message.recipient_email,
message.description,
message.date_recorded,
message.filename,
message.size_bytes,
message.size_time,
message.filepath,
message.Flag,
message.title,
message.date_activity,
member.member_image_url
FROM message
INNER JOIN member
ON message.sender_id = member.person_id
WHERE sender_id = (SELECT person_id FROM auth_key WHERE key = #Key)
OR recipient_id = (SELECT person_id FROM auth_key WHERE key = #Key)
AND Flag != 'DEL'
END
I suspect you need some extra parens to segment the logic in the manner you want:
WHERE (sender_id = (SELECT person_id FROM auth_key WHERE key = #Key)
OR recipient_id = (SELECT person_id FROM auth_key WHERE key = #Key))
AND Flag != 'DEL'

How to apply update query with IN operator using stored procedure

Question:
update tablename
set columnname = "12"
where columnname2 in ('1','2','3','4');
It will run with simple query.
How to run above query using a stored procedure i.e
update tablename
set columname = #param1
where columnname2 in (#param2);
where #param2 have '1','2' etc..
You should create a function which is used to delimit your comma seperated String..
CREATE FUNCTION SplitString
(
#Input NVARCHAR(MAX),
#Character CHAR(1)
)
RETURNS #Output TABLE (
Item NVARCHAR(1000)
)
AS
BEGIN
DECLARE #StartIndex INT, #EndIndex INT
SET #StartIndex = 1
IF SUBSTRING(#Input, LEN(#Input) - 1, LEN(#Input)) <> #Character
BEGIN
SET #Input = #Input + #Character
END
WHILE CHARINDEX(#Character, #Input) > 0
BEGIN
SET #EndIndex = CHARINDEX(#Character, #Input)
INSERT INTO #Output(Item)
SELECT SUBSTRING(#Input, #StartIndex, #EndIndex - 1)
SET #Input = SUBSTRING(#Input, #EndIndex + 1, LEN(#Input))
END
RETURN
END
GO
Now your update Query should be
Update tablename set columname=#param1
Where columnname2 in (SELECT Item FROM dbo.SplitString(#param2, ','))

Resources