How to convert procedure from SQL Server into Oracle? - sql-server

I am newbie to Oracle. I want to convert a procedure from SQL Server.
This is my procedure
ALTER PROCEDURE [dbo].[GETMONITORING]
#namabarang varchar (max)=null,
#PeriodeAwal varchar (max)=null,
#PeriodeAkhir varchar (max)=null,
#JenisLayanan varchar (max)=null
AS
BEGIN
SET NOCOUNT ON;
DECLARE
#nWhere varchar(4000),
#Select varchar(4000),
#from varchar(4000),
#Where varchar(4000),
#final varchar (4000)
SET #Select = 'select * '
SET #from = 'from table '
SET #where = 'where 1=1'
IF isnull(len(#namabarang), 0) <> 0
SET #where = ISNULL(#where, '') + ' and namabarang like ''' + ISNULL(#namabarang, '') + ''' '
IF isnull(len(#JenisLayanan), 0) <> 0
SET #where = ISNULL(#where, '') + 'and jenislayananid like ''' + ISNULL(#JenisLayanan, '') + ''' '
IF isnull(len(#PeriodeAwal), 0) <> 0 and isnull(len(#PeriodeAkhir), 0) <> 0
SET #where = ISNULL(#where, '') + ' and tanggalpermohonan between ' + #PeriodeAwal + ' and ' + #PeriodeAkhir
SET #final = #Select + #from + #where
execute (#final)
END
I have tried to convert to Oracle. This is my stored procedure in Oracle
create or replace PROCEDURE GETMONITORING
(
v_namabarang in varchar2 default null,
v_JenisLayanan in varchar2 default null
)
AS
v_where VARCHAR2(200);
v_Select VARCHAR2(200);
v_from VARCHAR2(200);
v_final VARCHAR2(200);
v_result VARCHAR2(200);
BEGIN
v_Select := 'select * ';
v_from := 'from permohonan ';
v_where := 'where sysdate=sysdate ';
if namabarang is not null
then v_where := v_where || ' and namabarang like '%' || v_namabarang || '%'';
if jenislayanan is not null
then v_where := v_where || 'and jenislayanan='||v_jenislayanan ;
v_final := v_select || v_from || v_where;
EXECUTE immediate v_final INTO v_result;
dbms_output.put_line(v_result);
END;
When I compile that stored procedure, I get an error:
Error(37,50): PLS-00103: Encountered the symbol "%" when expecting one of the following: * & = - + ; < / > at in is mod remainder not rem <> or != or ~= >= <= <> and or like like2 like4 likec between || member submultiset
Could you help me to fix this ?
Is my stored procedure in Oracle correct in logic?
How do I call that stored procedure in sqlplus ?
Thanks

You are missing the extra single quotes around the constants:
if namabarang is not null then
v_where :=v_where || ' and namabarang like ''%' || v_namabarang || '%';
end if;
if jenislayanan is not null then
v_where :=v_where || ' and jenislayanan = '''|| v_jenislayanan || '''';
end if;

Related

Oracle function exchange for SQL Server

I do an Oracle to SQL Server project,now I have a function that I can not rebuild,I don't know what is wrong,
The function is used to fetch the Oracle sequenes,the result is wrong.
Oracle function code
CREATE FUNCTION [test].[GETWORKORDERID] (numberPre varchar2)
return varchar2 is
PRAGMA AUTONOMOUS_TRANSACTION;
findId number(8); --maxid
nowNumber varchar2(50);
n_count number(8);
n_count2 number(8);
nowNumber2 varchar2(50);
begin
nowNumber := to_char(sysdate, 'yyyymmdd');
nowNumber2 := to_char(sysdate - 1, 'yyyymmdd');
select count(1)
into n_count2
from user_sequences t
where t.sequence_name = 'SEQ_' || numberPre || '_' || nowNumber2;
if n_count2 > 0 then
execute immediate 'drop sequence SEQ_' || numberPre || '_' ||
nowNumber2;
end if;
select count(1)
into n_count
from user_sequences t
where t.sequence_name = 'SEQ_' || numberPre || '_' || nowNumber;
if n_count = 0 then
execute immediate 'create sequence SEQ_' || numberPre || '_' ||
nowNumber ||
' minvalue 10000 maxvalue 99999999 start with 10000 increment by 1 NOCYCLE NOCACHE';
end if;
execute immediate 'select SEQ_' || numberPre || '_' || nowNumber ||
'.nextval from dual'
into findId;
commit;
return numberPre || nowNumber || findId;
end;**
I changed it for SQL Server to:
CREATE FUNCTION [test-CSR].[GETWORKORDERID]
(#numberPre nvarchar(max))
RETURNS TABLE
AS
BEGIN
DECLARE #findId bigint;
DECLARE #nowNumber bigint;
DECLARE #n_count bigint;
DECLARE #n_count2 bigint;
DECLARE #nowNumber2 bigint;
DECLARE #sql1 nvarchar(max);
DECLARE #sql2 nvarchar(max);
DECLARE #sql3 nvarchar(max);
DECLARE #sql4 nvarchar(max);
DECLARE #result nvarchar(max);
SET #nowNumber = CONVERT(varchar(30), GETDATE(), 20)
SET #nowNumber2 = CONVERT(varchar(30), GETDATE(), 20)
SELECT COUNT(1)
INTO n_count2
FROM user_sequences t
WHERE t.sequence_name = 'SEQ_' + numberPre + '_' + nowNumber2;
IF n_count2 > 0
BEGIN
SET #sql1 = 'drop sequence SEQ_' + numberPre + '_' + nowNumber2;
EXECUTE (#sql1)
END;
SELECT COUNT(1)
INTO n_count
FROM user_sequences t
WHERE t.sequence_name = 'SEQ_' + #numberPre + '_' + #nowNumber;
IF n_count = 0
BEGIN
SET #sql2 = 'create sequence SEQ_ ' + #numberPre + '_' + #nowNumber +
' minvalue 10000 maxvalue 99999999 start with 10000 increment by 1 NOCYCLE NOCACHE';
EXECUTE (#sql2)
END;
SET #sql3 = 'select SEQ_ ' + #numberPre + '_' + #nowNumber + '.NEXT VALUE FOR user_sequences';
SET #findId = #sql3;
SET #sql4 = #numberPre + #nowNumber + #findId;
INSERT INTO #result
EXEC (#sql4)
END;
Now I rebuild the function in SQL Server,but when SQL Server runs, the result is wrong, I don't know what the mistake is?
In functions you can not use EXECUTE. You try to create sequence. Functions in SQL Server are pure. They can not change objects and data in the database. I can suggest you to use a PROCEDURE instead of a FUNCTION.
If you declare a FUNCTION, it should be defined like this:
CREATE FUNCTION [test-CSR].[GETWORKORDERID]
(#numberPre nvarchar(max))
RETURNS #result TABLE (...)
AS
BEGIN
...
RETURN;
END
You should save count into variable like this:
SELECT #n_count2 = COUNT(1)
FROM user_sequences t
WHERE t.sequence_name = 'SEQ_' + numberPre + '_' + nowNumber2;
And then write:
IF #n_count2 > 0 ...
At the end you should remove INSERT INTO #result. Should be presented only EXEC (#sql4)
Hope, It can help you.
You'll have to change this to a procedure, if at all possible. There are some not-so-nice ways to run side-effecting functions in SQL Server, but they should be avoided. Check out the automatic translation that SQL Server Migration Assistant for Oracle for gory details.
Normally you should migrate to do things the "SQL Server way" when porting code.
Anyway, here's a idiomatic SQL Server translation of that procedure. But the whole process of dropping sequences is pretty strange.
--create schema [test-CSR]
go
CREATE or alter procedure [test-CSR].[GETWORKORDERID] #numberPre nvarchar(max), #result nvarchar(max) out
AS
/*
declare #result nvarchar(max)
exec [test-CSR].[GETWORKORDERID] N'foo', #result out
print #result
*/
BEGIN
DECLARE #findId bigint;
DECLARE #nowNumber bigint = CONVERT(varchar(30), GETDATE(), 112);
DECLARE #nowNumber2 bigint = CONVERT(varchar(30), GETDATE()-1, 112);
DECLARE #sql nvarchar(max);
declare #seq sysname = concat('SEQ_', #numberPre, '_', #nowNumber);
declare #seq2 sysname = concat('SEQ_', #numberPre, '_', #nowNumber2);
IF exists (select * from sys.sequences where name = #seq2)
BEGIN
SET #sql = concat('drop sequence ', quotename(#seq2));
--print #sql;
EXECUTE (#sql);
END;
IF not exists (select * from sys.sequences where name = #seq)
BEGIN
SET #sql = concat('create sequence ', quotename(#seq),
' start with 10000 increment by 1 minvalue 10000 maxvalue 99999999 NO CYCLE NO CACHE');
--print #sql;
EXECUTE (#sql)
END;
SET #sql = concat('select #findId = NEXT VALUE FOR ', quotename(#seq)) ;
--print #sql;
exec sp_executesql #sql, N'#findId bigint out', #findId = #findId out;
set #result = concat(#numberPre, #nowNumber, #findId);
END;
If you can make the change I would probably have a single sequence object, and pass the next value for that into a function like this:
create sequence WORKORDERID_seq start with 10000 increment by 1 minvalue 10000 maxvalue 99999999 NO CYCLE NO CACHE
go
create function [test-CSR].[GETWORKORDERID2] (#nowNumber nvarchar(max), #nv int)
returns nvarchar(max)
as
begin
return concat(CONVERT(varchar(30), GETDATE(), 112),#nowNumber,#nv)
end
and run a batch job to reset the sequence value every night.

mssql dynamic query entity does not get values

hello this my dynamic query and this procedure I did tested is working.
but Does not bring data to the server-side (entity)
visual studio 2012
framework 4.5
entity store procedure
public IEnumerable<spGetInvoiceDetailSearch_Result> GetInvoiceDetailedSearch(InvoiceModel item)
{
return DALContext.GetInvoiceDetailedSearch(item);
}
ALTER PROCEDURE [dbo].[spGetInvoiceDetailSearch] #InvoiceItemID INT
,#InvoiceTypeID INT
,#VesselID INT
,#PaidBy NVARCHAR(50)
,#InvoiceNo NVARCHAR(50)
,#CompanyID INT
,#InvoiceFromDate DATE
,#InvoiceToDate DATE
,#FromDueDate DATE
,#ToDueDate DATE
,#FromAmount DECIMAL(18, 4)
,#ToAmount DECIMAL(18, 4)
,#DueDateType NVARCHAR(50)
AS
BEGIN
DECLARE #SQLQuery AS NVARCHAR(4000)
SELECT #SQLQuery =
'SELECT dbo.Invoices.InvoiceID, dbo.Invoices.CompanyID, dbo.Invoices.VesselID, dbo.Invoices.InvoiceNo, dbo.Invoices.DueDate, dbo.Invoices.Amount,
dbo.Invoices.Comment, dbo.Invoices.IsPaid, dbo.Invoices.PaymentDate, dbo.Invoices.PaidBy, dbo.Invoices.Period, dbo.Invoices.InvoiceDate,
dbo.Invoices.InvoiceCurrencyCode, dbo.Invoices.InvoiceAmount, dbo.Invoices.IsReceived, dbo.Invoices.IsProforma, dbo.Invoices.InvoiceTypeID,
dbo.Invoices.IsDeleted, dbo.Invoices.Parity, dbo.Invoices.DueDateType, dbo.Vessels.Name AS VesselName, dbo.InvoiceVsInvoiceItems.ItemPrice as ItemPrice,
dbo.InvoiceVsInvoiceItems.InvoiceItemID as InvoiceItemID, dbo.InvoiceVsInvoiceItems.VAT as VAT, dbo.InvoiceVsInvoiceItems.ItemType as ItemType, dbo.InvoiceItems.Name AS InvoiceItemName,
dbo.Companies.Name AS CompanyName, dbo.InvoiceTypes.Name AS InvoiceTypeName
FROM dbo.Invoices LEFT OUTER JOIN
dbo.Companies ON dbo.Invoices.CompanyID = dbo.Companies.CompanyID LEFT OUTER JOIN
dbo.InvoiceTypes ON dbo.Invoices.InvoiceTypeID = dbo.InvoiceTypes.InvoiceTypeID LEFT OUTER JOIN
dbo.InvoiceVsInvoiceItems ON dbo.Invoices.InvoiceID = dbo.InvoiceVsInvoiceItems.InvoiceID LEFT OUTER JOIN
dbo.InvoiceItems ON dbo.InvoiceVsInvoiceItems.InvoiceVsInvoiceItemID = dbo.InvoiceItems.InvoiceItemID LEFT OUTER JOIN
dbo.Vessels ON dbo.Invoices.VesselID = dbo.Vessels.VesselID WHERE
dbo.Invoices.IsDeleted != 1
and dbo.Vessels.IsDeleted != 1
and dbo.Companies.IsDeleted != 1 '
SET FMTONLY OFF
IF #InvoiceItemID > 0
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.InvoiceItems.InvoiceItemID= ''' + CAST(#InvoiceItemID AS NVARCHAR(50)) + ''''
END
IF #InvoiceTypeID > 0
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.InvoiceTypeID= ''' + CAST(#InvoiceTypeID AS NVARCHAR(50)) + ''''
END
IF #VesselID > 0
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.VesselID= ''' + CAST(#VesselID AS NVARCHAR(50)) + ''''
END
IF #PaidBy IS NOT NULL
BEGIN
SET #SQLQuery = #SQLQuery + 'AND dbo.Invoices.PaidBy = ''' + CAST(#PaidBy AS NVARCHAR(50)) + ''''
END
IF #InvoiceNo IS NOT NULL
BEGIN
SET #SQLQuery = #SQLQuery + 'AND dbo.Invoices.InvoiceNo = ''' + CAST(#InvoiceNo AS NVARCHAR(50)) + ''''
END
IF #CompanyID > 0
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.CompanyID = ''' + CAST(#CompanyID AS NVARCHAR(50)) + ''''
END
IF #FromAmount IS NOT NULL AND #ToAmount IS NOT NULL
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.Amount BETWEEN ''' + CAST(#FromAmount AS NVARCHAR(100)) + ''' AND ''' + CAST(#ToAmount AS NVARCHAR(100)) + ''''
END
IF #DueDateType IS NOT NULL
BEGIN
SET #SQLQuery = #SQLQuery + 'AND dbo.Invoices.DueDateType = ''' + CAST(#DueDateType AS NVARCHAR(50)) + ''''
END
IF #InvoiceFromDate IS NOT NULL AND #InvoiceToDate IS NOT NULL
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.InvoiceDate Between ''' + CAST(#InvoiceFromDate AS NVARCHAR(100)) + ''' AND ''' + CAST(#InvoiceToDate AS NVARCHAR(100)) + ''''
END
IF #FromDueDate IS NOT NULL AND #ToDueDate IS NOT NULL
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.DueDate Between ''' + CAST(#FromDueDate AS NVARCHAR(100)) + ''' AND ''' + CAST(#ToDueDate AS NVARCHAR(100)) + ''''
END
EXECUTE (#SQLQuery)
END
and end question
my table date type : date format but
server shows it like datetime how can I do to change it to date format..
thank you
regards
ALTER PROCEDURE [dbo].[spGetInvoiceDetailSearch] #InvoiceItemID INT
,#InvoiceTypeID INT
,#VesselID INT
,#PaidBy NVARCHAR(50)
,#InvoiceNo NVARCHAR(50)
,#CompanyID INT
,#InvoiceFromDate DATE
,#InvoiceToDate DATE
,#FromDueDate DATE
,#ToDueDate DATE
,#FromAmount DECIMAL(18, 4)
,#ToAmount DECIMAL(18, 4)
,#DueDateType NVARCHAR(50)
AS
BEGIN
DECLARE #SQLQuery AS NVARCHAR(4000)
SELECT #SQLQuery =
'SELECT dbo.Invoices.InvoiceID, dbo.Invoices.CompanyID, dbo.Invoices.VesselID, dbo.Invoices.InvoiceNo, dbo.Invoices.DueDate, dbo.Invoices.Amount,
dbo.Invoices.Comment, dbo.Invoices.IsPaid, dbo.Invoices.PaymentDate, dbo.Invoices.PaidBy, dbo.Invoices.Period, dbo.Invoices.InvoiceDate,
dbo.Invoices.InvoiceCurrencyCode, dbo.Invoices.InvoiceAmount, dbo.Invoices.IsReceived, dbo.Invoices.IsProforma, dbo.Invoices.InvoiceTypeID,
dbo.Invoices.IsDeleted, dbo.Invoices.Parity, dbo.Invoices.DueDateType, dbo.Vessels.Name AS VesselName, dbo.InvoiceVsInvoiceItems.ItemPrice as ItemPrice,
dbo.InvoiceVsInvoiceItems.InvoiceItemID as InvoiceItemID, dbo.InvoiceVsInvoiceItems.VAT as VAT, dbo.InvoiceVsInvoiceItems.ItemType as ItemType, dbo.InvoiceItems.Name AS InvoiceItemName,
dbo.Companies.Name AS CompanyName, dbo.InvoiceTypes.Name AS InvoiceTypeName
FROM dbo.Invoices LEFT OUTER JOIN
dbo.Companies ON dbo.Invoices.CompanyID = dbo.Companies.CompanyID LEFT OUTER JOIN
dbo.InvoiceTypes ON dbo.Invoices.InvoiceTypeID = dbo.InvoiceTypes.InvoiceTypeID LEFT OUTER JOIN
dbo.InvoiceVsInvoiceItems ON dbo.Invoices.InvoiceID = dbo.InvoiceVsInvoiceItems.InvoiceID LEFT OUTER JOIN
dbo.InvoiceItems ON dbo.InvoiceVsInvoiceItems.InvoiceVsInvoiceItemID = dbo.InvoiceItems.InvoiceItemID LEFT OUTER JOIN
dbo.Vessels ON dbo.Invoices.VesselID = dbo.Vessels.VesselID WHERE
dbo.Invoices.IsDeleted != 1
and dbo.Vessels.IsDeleted != 1
and dbo.Companies.IsDeleted != 1 '
SET FMTONLY OFF
IF #InvoiceItemID > 0
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.InvoiceItems.InvoiceItemID= ' + CAST(#InvoiceItemID AS NVARCHAR(50)) + ''
END
IF #InvoiceTypeID > 0
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.InvoiceTypeID= ' + CAST(#InvoiceTypeID AS NVARCHAR(50)) + ''
END
IF #VesselID > 0
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.VesselID= ' + CAST(#VesselID AS NVARCHAR(50)) + ''
END
IF #PaidBy IS NOT NULL
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.PaidBy = ''' + CAST(#PaidBy AS NVARCHAR(50)) + ''''
END
IF #InvoiceNo IS NOT NULL
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.InvoiceNo = ''' + CAST(#InvoiceNo AS NVARCHAR(50)) + ''''
END
IF #CompanyID > 0
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.CompanyID = ' + CAST(#CompanyID AS NVARCHAR(50)) + ''
END
IF #FromAmount IS NOT NULL AND #ToAmount IS NOT NULL
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.Amount BETWEEN ''' + CAST(#FromAmount AS NVARCHAR(100)) + ''' AND ''' + CAST(#ToAmount AS NVARCHAR(100)) + ''''
END
IF #DueDateType IS NOT NULL
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.DueDateType = ''' + CAST(#DueDateType AS NVARCHAR(50)) + ''''
END
IF #InvoiceFromDate IS NOT NULL AND #InvoiceToDate IS NOT NULL
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.InvoiceDate Between ''' + CAST(#InvoiceFromDate AS NVARCHAR(100)) + ''' AND ''' + CAST(#InvoiceToDate AS NVARCHAR(100)) + ''''
END
IF #FromDueDate IS NOT NULL AND #ToDueDate IS NOT NULL
BEGIN
SET #SQLQuery = #SQLQuery + ' AND dbo.Invoices.DueDate Between ''' + CAST(#FromDueDate AS NVARCHAR(100)) + ''' AND ''' + CAST(#ToDueDate AS NVARCHAR(100)) + ''''
END
PRINT (#SQLQuery)
END
First of all, debugging it's very easy. Replace EXEC(#SQLQUery) with print and then you see your actual query.
You had some sintax error ( some places where AND was missing a space in front) and also you have some interger that were treated as strings.
Try my updated procedure.
It seems that procedure is getting called properly but no rows are getting returned, to debug the exact problem you can write actual hardcoded query returning 1 or more records instead of dynamic query.
So after doing that there are two possibilities
procedure call via edmx returns data, that means parameter values are causing some problem.
Any Data is not returned.
To solve any of the problem you need to check corresponding sql query which is getting generated while calling SP via Enitity Framework.

Incremental batch delete and insert actions very slow in SQL Server

I have the following stored procedure which deletes and inserts rows in a table. It is running slow.
I have read various proposals and i have implemented:
Delete rows in batches and using derived table
Disable FK
Indexes on fields that are in the where clause.
So the way it should go is:
Tables have around 10 million records.
Every day i need to refresh around 15-30% of them. I use this SP to do it.
Source:
CREATE PROCEDURE [dbo].[spIncrementalUpdate]
-- Add the parameters for the stored procedure here
#table_inc nvarchar(30),
#table_target nvarchar(30),
#table_date nvarchar(30),
#field1 nvarchar(10),
#field2 nvarchar(10)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #logmessage as nvarchar(2048)
DECLARE #logdatacode as int
DECLARE #cmd as nvarchar(max)
DECLARE #fromjulian nvarchar(10)
DECLARE #datadate datetime
DECLARE #datadate_str nvarchar(10)
DECLARE #rows int
DECLARE #ParmDefinition nvarchar(500)
select #fromjulian = '114000'
print 'Using ' + #fromjulian
--
-- GET THE ROW COUNT OF THE INC TABLE.
--
IF #field2 = ''
BEGIN
SET #cmd = N'SELECT #retval = count(*) from ' +
#table_inc + ' where ' + #field1 +' > ' + #fromjulian
END
ELSE
BEGIN
SET #cmd = N'SELECT #retval = count(*) from ' +
#table_inc + ' where ' + #field1 +' > ' + #fromjulian +
' OR ' + #field2 +' > ' + #fromjulian
END
SET #ParmDefinition = N'#retval int OUTPUT'
EXEC sp_executesql #cmd, #ParmDefinition, #retval = #rows OUTPUT
--
if #rows <> 0
BEGIN
SET #logmessage = #table_inc + ' has ' +
cast(#rows as nvarchar(10)) +
' rows after ' + #fromjulian + ', deleting'
SET #logdatacode = 1000
--
-- Delete the records from original table based on #fromjulian
--
IF #field2 = ''
BEGIN
SET #cmd = N'delete ' + #table_target +
' from (select top(50000) * from ' + #table_target +
' where ' + #field1 + ' > ' + #fromjulian +
' order by ' + #field1 + ') ' +
#table_target
print #cmd
END
ELSE
BEGIN
SET #cmd = N'delete ' + #table_target +
' from (select top(50000) * from ' +
#table_target +
' where ' + #field1 + ' > ' + #fromjulian +
' OR ' + #field2 +' > ' + #fromjulian +
' order by ' + #field1 + ',' + #field2 + ') ' +
#table_target
print #cmd
END
SELECT 1
WHILE ##ROWCOUNT <> 0
BEGIN
EXEC sp_executesql #cmd
END
--
-- Inserting the records to target from INC table
--
IF #field2 = ''
BEGIN
SET #cmd = N'insert into ' + #table_target +
' select * from ' + #table_inc +
' where ' + #field1 +' > ' + cast(#fromjulian as nvarchar(10))
print #cmd
END
ELSE
BEGIN
SET #cmd = N'insert into ' + #table_target +
' select * from ' + #table_inc +
' where ' + #field1 +' > ' + cast(#fromjulian as nvarchar(10)) +
' OR ' + #field2 +' > ' + cast(#fromjulian as nvarchar(10))
print #cmd
END
print #cmd
EXEC sp_executesql #cmd
END
ELSE
BEGIN
SET #logmessage = 'NO ROWS IN ' + #table_inc + ' AFTER ' + cast(#fromjulian as nvarchar(10))
SET #logdatacode = 1001
END
--
-- LOG
--
INSERT INTO YLA_GROUP.[dbo].[sysssislog]
([event]
,[computer]
,[operator]
,[source]
,[sourceid]
,[executionid]
,[starttime]
,[endtime]
,[datacode]
,[databytes]
,[message])
VALUES
('spIncrementalUpdate','','','',NEWID(),NEWID(),getdate(),getdate(),#logdatacode,null,#logmessage)
print cast(#logdatacode as nvarchar(10)) + ' - ' + #logmessage
END
Since you are deleting rows in batches, you should remove the ORDER BY clause from your subquery because it is not necessary.
Here's the extract from your script:
IF #field2 = ''
BEGIN
SET #cmd = N'delete ' + #table_target +
' from (select top(50000) * from ' + #table_target +
' where ' + #field1 + ' > ' + #fromjulian + ') ' + #table_target
print #cmd
END
ELSE
BEGIN
SET #cmd = N'delete ' + #table_target +
' from (select top(50000) * from ' + #table_target +
' where ' + #field1 + ' > ' + #fromjulian +
' OR ' + #field2 +' > ' + #fromjulian + ') ' + #table_target
print #cmd
END
Remember that sorting can be an expensive operation, and even more expensive if you remove (correctly in this case) indexes.
Beyond that, there's not much you can do. Also consider that using dynamic SQL, execution plans are not cached. So, every time you execute the command inside #cmd the Query Engine needs to calculate the optimal execution plan. Unfortunately, as far as I can see, you need dynamic SQL.

Stored Procedure not Working according to need

What am I doing wrong? My stored procedure is not working according to need when using =, >, < as a parameter please help
Here is my stored procedure:
ALTER PROCEDURE [dbo].[storedp_Search]
#pAccountTypeId int = null,
#pFirstName varchar(25) = null,
#pLastName varchar(35) = null,
#pZip varchar(10) = null,
#pOperator varchar(2) = null,
#pRating varchar(2) = null
AS
BEGIN
SET NOCOUNT ON;
Declare #SQLQuery AS NVarchar(4000)
SET #SQLQuery = 'select
at.AccountName,
U.UserId, U.FirstName, U.LastName,
U.NMLS, U.[Address], U.PrimaryEmailId As Office,
U.AdditionalEmail As Personal,
U.DirectPhone As Work, U.Mobile,
R.RatingStar
from
[User] U
left outer join
RatingReview R on R.UserId = U.UserId
left outer join
AccountType at on at.AccountTypeId = U.AccountTypeId
where U.Deleted = 0
AND at.AccountTypeId = '+CAST(#pAccountTypeId as Varchar(10))+'
AND U.FirstName = ''' + #pFirstName + '''
AND U.LastName = ''' + #pLastName + '''
AND U.Zip = ''' + #pZip + '''
AND R.RatingStar = ''' + #pRating + ''''
IF(#pAccountTypeId != null OR #pAccountTypeId != '')
BEGIN
SET #SQLQuery = #SQLQuery + ' AND at.AccountTypeId='+CONVERT(VARCHAR, #pAccountTypeId )
END
IF(#pFirstName != null OR #pFirstName != '')
BEGIN
SET #SQLQuery=#SQLQuery+' AND U.FirstName Like ''%' + #pFirstName + '%'''
END
IF(#pLastName !=null OR #pLastName != '')
BEGIN
SET #SQLQuery=#SQLQuery+' AND U.LastName Like ''%' + #pLastName + '%'''
END
IF(#pZip !=null OR #pZip != '')
BEGIN
SET #SQLQuery=#SQLQuery+' AND U.Zip Like ''%' + #pZip + '%'''
END
IF(#pOperator = '=')
BEGIN
SET #SQLQuery += ' AND r.ratingstar = ' + CAST(#pRating AS NVARCHAR(5)) + ''
END
IF(#pOperator = '>')
BEGIN
SET #SQLQuery += ' AND r.ratingstar < ' + CAST(#pRating AS NVARCHAR(5)) + ''
END
IF(#pOperator = '<')
BEGIN
SET #SQLQuery += ' AND r.ratingstar > ' + CAST(#pRating AS NVARCHAR(5)) + ''
END
SET #SQLQuery=#SQLQuery+
'group by
at.AccountName,
U.UserId,
U.FirstName,
U.LastName,
U.NMLS,
U.[Address],
U.PrimaryEmailId,
U.AdditionalEmail,
U.DirectPhone,
U.Mobile,
R.RatingStar'
EXEC (#SQLQuery)
END
when i am using following exec statement its working fine
Execute storedp_Search 1,'Mark','Smith','48393','=','5'
but when using the same with different conditions then its not working.
Execute storedp_Search 1,'Mark','Smith','48393','>','4'
Try this,
I think you misspelled the operator inside the if condition, if i'm not wrong
ALTER PROCEDURE [dbo].[Storedp_Search] #pAccountTypeId INT =NULL,
#pFirstName VARCHAR(25)=NULL,
#pLastName VARCHAR(35)=NULL,
#pZip VARCHAR(10)=NULL,
#pOperator VARCHAR(2)=NULL,
#pRating VARCHAR(2)=NULL
AS
BEGIN
SET NOCOUNT ON;
DECLARE #SQLQuery AS NVARCHAR(4000)
SET #SQLQuery= 'select
at.AccountName,
U.UserId,
U.FirstName,
U.LastName,
U.NMLS,
U.[Address],
U.PrimaryEmailId As Office,
U.AdditionalEmail As Personal,
U.DirectPhone As Work,
U.Mobile,
R.RatingStar
from [User] U
left outer join RatingReview R on R.UserId =U.UserId
left outer join AccountType at on at.AccountTypeId = U.AccountTypeId
where U.Deleted =0
AND at.AccountTypeId = '
+ Cast(#pAccountTypeId AS VARCHAR(10))
+ '
AND U.FirstName = ''' + #pFirstName
+ '''
AND U.LastName = ''' + #pLastName
+ '''
AND U.Zip = ''' + #pZip
+ '''
AND R.RatingStar = ''' + #pRating + ''''
IF( #pAccountTypeId IS NOT NULL
OR #pAccountTypeId != '' )
BEGIN
SET #SQLQuery=#SQLQuery + ' AND at.AccountTypeId='
+ CONVERT(VARCHAR, #pAccountTypeId )
END
IF( #pFirstName IS NOT NULL
OR #pFirstName != '' )
BEGIN
SET #SQLQuery=#SQLQuery + ' AND U.FirstName Like ''%'
+ #pFirstName + '%'''
END
IF( #pLastName IS NOT NULL
OR #pLastName != '' )
BEGIN
SET #SQLQuery=#SQLQuery + ' AND U.LastName Like ''%'
+ #pLastName + '%'''
END
IF( #pZip IS NOT NULL
OR #pZip != '' )
BEGIN
SET #SQLQuery=#SQLQuery + ' AND U.Zip Like ''%' + #pZip + '%'''
END
IF( #pOperator = '=' )
BEGIN
SET #SQLQuery += ' AND r.ratingstar = '
+ Cast(#pRating AS NVARCHAR(5)) + ''
END
IF( #pOperator = '>' )
BEGIN
SET #SQLQuery += ' AND r.ratingstar > '
+ Cast(#pRating AS NVARCHAR(5)) + ''
END
IF( #pOperator = '<' )
BEGIN
SET #SQLQuery += ' AND r.ratingstar < '
+ Cast(#pRating AS NVARCHAR(5)) + ''
END
SET #SQLQuery=#SQLQuery + 'group by
at.AccountName,
U.UserId,
U.FirstName,
U.LastName,
U.NMLS,
U.[Address],
U.PrimaryEmailId,
U.AdditionalEmail,
U.DirectPhone,
U.Mobile,
R.RatingStar'
EXEC ( #SQLQuery )
END

SQL Error: Incorrect syntax near the keyword 'End'

Need help with this SQL Server 2000 procedure. The problem is made difficult because I'm testing procedure via Oracle SQL Developer.
I'm running the procedure to iterate column with new sequence of numbers in Varchar format for those who have null values.
But I keep getting error, so a) I may have done a wrong approach b) syntax is incorrect due to version used. I'm primarily Oracle user.
Error I keep getting: SQL Error: Incorrect syntax near the keyword 'End'. which isn't helpful enough to fix it out. The End refers to the very last 'End' in the procedure.
Any help would be greatly appreciated.
Here's the Procedure.
ALTER PROCEDURE [dbo].[OF_AUTOSEQUENCE] #JvarTable Varchar(250), #varColumn Varchar(250), #optIsString char(1), #optInterval int AS
/*
Procedure OF_AUTOSEQUENCE
Created by Joshua [Surname omitted]
When 20100902
Purpose To fill up column with new sequence numbers
Arguments varTable - Table name
varColumn - Column name
optIsString - Option: is it string or numeric, either use T(rue) or F(alse)
optInterval - Steps in increment in building new sequence (Should be 1 (one))
Example script to begin procedure
EXECUTE [dbo].[OF_AUTOSEQUENCE] 'dbo.EH_BrownBin', 'Match', 'T', 1
Any questions about this, please send email to
[business email omitted]
*/
declare
#topseed int,
#stg_topseed varchar(100),
#Sql_string nvarchar(4000),
#myERROR int,
#myRowCount int
set #Sql_string = 'Declare MyCur CURSOR FOR select ' + #varColumn + ' from ' + #JvarTable + ' where ' + #varColumn + ' is null'
Exec sp_executesql #Sql_string
SET NOCOUNT ON
Begin
if #optIsString = 'T'
Begin
set #Sql_string = 'select top 1 ' + #varColumn + ' from ' + #JvarTable + ' order by convert(int, ' + #varColumn + ') desc'
set #stg_topseed = #Sql_string
set #topseed = convert(int, #stg_topseed)
ENd
else
Begin
set #Sql_string = 'select top 1 ' + #varColumn + ' from ' + #JvarTable + ' order by ' + #varColumn + ' desc'
set #topseed = #Sql_string
ENd
-- SELECT #myERROR = ##ERROR, #myRowCOUNT = ##ROWCOUNT
-- IF #myERROR != 0 GOTO HANDLE_ERROR
open MyCur
fetch next from MyCur
WHILE ##FETCH_STATUS = 0
set #topseed = #topseed + #optInterval
if #optIsString = 'T'
begin
set #Sql_string = 'update ' + #JvarTable + ' set ' + #varColumn + ' = cast((' + #topseed + ') as char) where current of ' + MyCur
exec (#Sql_string)
ENd
else
begin
set #Sql_string = 'update ' + #JvarTable + ' set ' + #varColumn + ' = ' + #topseed + ' where current of ' + MyCur
exec (#Sql_string)
ENd
fetch next from MyCur
ENd
-- SELECT #myERROR = ##ERROR, #myRowCOUNT = ##ROWCOUNT
-- IF #myERROR != 0 GOTO HANDLE_ERROR
--HANDLE_ERROR:
--print #myERROR
CLOSE MyCur
DEALLOCATE MyCur
End
you're missing a begin right after the WHILE. You indented like you want a block (multiple statements) in the while loop, and even have a end for the while, but no begin.
make it:
...
open MyCur
fetch next from MyCur
WHILE ##FETCH_STATUS = 0
begin --<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<add this
set #topseed = #topseed + #optInterval
if #optIsString = 'T'
begin
set #Sql_string = 'update ' + #JvarTable + ' set ' + #varColumn + ' = cast((' + #topseed + ') as char) where current of ' + MyCur
exec (#Sql_string)
ENd
else
begin
set #Sql_string = 'update ' + #JvarTable + ' set ' + #varColumn + ' = ' + #topseed + ' where current of ' + MyCur
exec (#Sql_string)
ENd
fetch next from MyCur
ENd
...

Resources