Replacing subquery in Snowflake - snowflake-cloud-data-platform

I am new to Snowflake SQL and trying to migrate a code from Oracle SQL to Snowflake SQL.
I am using a subquery in Oracle which is not supported in Snowflake and it gives the following err-r
SQL compilation error: Unsupported subquery type cannot be evaluated.
Original SQL Query -
select p."EMPLOYEE#" as Employee_ID,
(select o."POSITION_NO" from ah_occupancy o where o."EMPLOYEE_NO" = p."EMPLOYEE#" and o."JOB_NO" = p."JOB#" and p."WORKDATE" between o."PORTION_START" and o."PORTION_END") as Position_ID,
j."COMPANY_CODE",
date(p."WORKDATE") as Work_Date,
p."UNIT" as Calculated_Quantity,
p."PAYCODE"
from
"ODS"."HRIS"."PEPAYTRAN" p, job j
where p."EMPLOYEE#" =j."EMPLOYEE#"
and p."JOB#" = j."JOB#"
and date( p."WORKDATE") between '2021-02-04' and '2021-02-10'-->='11-FEB-2021'
and p."ORIGIN" not in ('RC101','FC801','WK8276')
and p."PAYCODE" not in ('GPPL', 'CLAMS')
and p."PAYCODE" not like 'JK%'
and p."TP" >= '01-JAN-2021'
and nvl(p."BATCH#",' ') not in ('MUHTSL','MUHTS','ICWTS','RDOAC','NU011','1')) ;
I reframed the query and it compiles and gives the same number of records, can anyone review the code and comment if its the same or if its in correct, kindly comment on same.
select p."EMPLOYEE#" as Employee_ID,
o.position_no as Position_ID,
j."COMPANY_CODE",
date(p."WORKDATE") as Work_Date,
p."UNIT" as Calculated_Quantity,
p."PAYCODE"
from
"ODS"."HRIS"."PEPAYTRAN" p, "ODS"."HRIS"."JOB" j, "ODS"."HRIS"."AH_OCCUPANCY" o
where p."EMPLOYEE#" =j."EMPLOYEE#"
and p."JOB#" = j."JOB#"
and date( p."WORKDATE") between '2021-02-04' and '2021-02-10'-->='11-FEB-2021'
and p."ORIGIN" not in ('RC101','FC801','WK8276')
and p."PAYCODE" not in ('GPPL', 'CLAMS')
and p."PAYCODE" not like 'JK%'
and p."TP" >= '01-JAN-2021'
and nvl(p."BATCH#",' ') not in ('MUHTSL','MUHTS','ICWTS','RDOAC','NU011','1')
and o."EMPLOYEE_NO" = p."EMPLOYEE#" and o."JOB_NO" = p."JOB#" and p."WORKDATE" between o."PORTION_START" and o."PORTION_END"

Both queries are equivalent. You can check that both return the same information by running the following query:
--original query
select
p."EMPLOYEE#" as Employee_ID,
(select
o."POSITION_NO"
from
ah_occupancy o
where
o."EMPLOYEE_NO" = p."EMPLOYEE#"
and o."JOB_NO" = p."JOB#"
and p."WORKDATE" between o."PORTION_START" and o."PORTION_END"
) as Position_ID,
j."COMPANY_CODE",
date(p."WORKDATE") as Work_Date,
p."UNIT" as Calculated_Quantity,
p."PAYCODE"
from
"ODS"."HRIS"."PEPAYTRAN" p,
job j
where
p."EMPLOYEE#" =j."EMPLOYEE#"
and p."JOB#" = j."JOB#"
and date( p."WORKDATE") between '2021-02-04' and '2021-02-10'-->='11-FEB-2021'
and p."ORIGIN" not in ('RC101','FC801','WK8276')
and p."PAYCODE" not in ('GPPL', 'CLAMS')
and p."PAYCODE" not like 'JK%'
and p."TP" >= '01-JAN-2021'
and nvl(p."BATCH#",' ') not in ('MUHTSL','MUHTS','ICWTS','RDOAC','NU011','1')) ;
minus
--new query
select
p."EMPLOYEE#" as Employee_ID,
o.position_no as Position_ID,
j."COMPANY_CODE",
date(p."WORKDATE") as Work_Date,
p."UNIT" as Calculated_Quantity,
p."PAYCODE"
from
"ODS"."HRIS"."PEPAYTRAN" p,
"ODS"."HRIS"."JOB" j,
"ODS"."HRIS"."AH_OCCUPANCY" o
where
p."EMPLOYEE#" =j."EMPLOYEE#"
and p."JOB#" = j."JOB#"
and date( p."WORKDATE") between '2021-02-04' and '2021-02-10'-->='11-FEB-2021'
and p."ORIGIN" not in ('RC101','FC801','WK8276')
and p."PAYCODE" not in ('GPPL', 'CLAMS')
and p."PAYCODE" not like 'JK%'
and p."TP" >= '01-JAN-2021'
and nvl(p."BATCH#",' ') not in ('MUHTSL','MUHTS','ICWTS','RDOAC','NU011','1')
and o."EMPLOYEE_NO" = p."EMPLOYEE#"
and o."JOB_NO" = p."JOB#"
and p."WORKDATE" between o."PORTION_START" and o."PORTION_END"
You can also try the following query which is also equivalent:
select
p."EMPLOYEE#" as Employee_ID,
o.position_no as Position_ID,
j."COMPANY_CODE",
date(p."WORKDATE") as Work_Date,
p."UNIT" as Calculated_Quantity,
p."PAYCODE"
from
"ODS"."HRIS"."PEPAYTRAN" p
inner join "ODS"."HRIS"."JOB" j
on (p."EMPLOYEE#" =j."EMPLOYEE#"
and p."JOB#" = j."JOB#")
inner join "ODS"."HRIS"."AH_OCCUPANCY" o
on (o."EMPLOYEE_NO" = p."EMPLOYEE#"
and o."JOB_NO" = p."JOB#"
and p."WORKDATE" between o."PORTION_START" and o."PORTION_END" )
where
date( p."WORKDATE") between '2021-02-04' and '2021-02-10'-->='11-FEB-2021'
and p."ORIGIN" not in ('RC101','FC801','WK8276')
and p."PAYCODE" not in ('GPPL', 'CLAMS')
and p."PAYCODE" not like 'JK%'
and p."TP" >= '01-JAN-2021'
and nvl(p."BATCH#",' ') not in ('MUHTSL','MUHTS','ICWTS','RDOAC','NU011','1')

Related

How to add data in a test class Apex

I already created a test class, simple test class, but I cant give data to it, Somebody can explain me a little please here is my code, when i Run the test the cover is 14 % and I dont know how to give data, for exceptions and made it at leas the 75 %
public void cargaPacientes () {
lMSD = new List<Enrollee__c>();
bLista = true;
String strCredencial = '';
String strPoliza = '';
String strCertificado = '';
String strRfc = '';
String fNacimiento = '';
String nombres = '';
String Aseguradora = '';
String Contratante = '';
String query = '';
Boolean correcto = true;
integer cuentacriterios = 0;
string producto = '';
if (proveedor.Tipo_de_Proveedor__c == 'Dentista' || proveedor.Tipo_de_Proveedor__c == 'Clínica' || proveedor.Tipo_de_Proveedor__c == 'Hospital'){
producto = 'Dental';
}else if (proveedor.Tipo_de_Proveedor__c == 'Óptica'){
producto = 'Visión';
}
if((msd.DENTEGRA_ID_Number__c != null) && (msd.DENTEGRA_ID_Number__c != '')) {
strCredencial = ' and DENTEGRA_ID_Number__c like \'' + msd.DENTEGRA_ID_Number__c + '\'';
System.debug(':::: strCredencial = ' + strCredencial);
cuentacriterios = cuentacriterios + 1;
}
if((msd.Family_Number__c != null) && (msd.Family_Number__c != '')){
strCertificado = ' and Family_Number__c like \'' + msd.Family_Number__c + '\'';
System.debug(':::: strCertificado = ' + strCertificado);
cuentacriterios = cuentacriterios + 1;
}
if((msd.RFC__c != null) && (msd.RFC__c != '')){
strRfc = ' and RFC__c like \'%' + msd.RFC__c + '%\'';
System.debug(':::: strRfc = ' + strRfc);
cuentacriterios = cuentacriterios + 1;
}
if((msd.Policy_Number__c != null) && (msd.Policy_Number__c != '')){
strPoliza = ' and Policy_Number__c like \'%' + msd.Policy_Number__c + '%\' ';
System.debug(':::: strPoliza = ' + strPoliza);
cuentacriterios = cuentacriterios + 1;
}
if(msd.Birth_Date__c != null) {
fNacimiento = ' and Birth_Date__c = ' + String.valueOf(msd.Birth_Date__c);
System.debug(':::: fNacimiento = ' + fNacimiento);
cuentacriterios = cuentacriterios + 1;
}
if(msd.Name != null) {
nombres = ' and Name like \'%' + msd.Name + '%\' ';
System.debug(':::: nombres = ' + nombres);
cuentacriterios = cuentacriterios + 1;
}
if(msd.Contratante__c != null) {
Contratante = ' and Contratante__c like \'%' + msd.Contratante__c + '%\' ';
System.debug(':::: Contratante = ' + Contratante);
cuentacriterios = cuentacriterios + 1;
}
if(msd.Aseguradora__c != null) {
Aseguradora = ' and Aseguradora__c like \'%' + msd.Aseguradora__c + '%\' ';
System.debug(':::: Aseguradora = ' + Aseguradora);
cuentacriterios = cuentacriterios + 1;
}
//if(strCredencial != '' || strCertificado != '' || strRfc != '' || strPoliza != '' || fNacimiento != '' || nombres != '') {
if(cuentacriterios>1){
//query = 'Select e.Contact__c, e.Id, e.Name, e.Policy_Number__c, e.Family_Number__c, e.RFC__c, e.Birth_Date__c from Enrollee__c e where Cve_tipo_registro__c = \'Elegibilidad\' and OwnerId = \'' + userID + '\'' + strCredencial + strCertificado + strRfc + strPoliza + fNacimiento;
query = 'Select e.Contact__c, e.Id, e.Name, e.Policy_Number__c, e.Family_Number__c, e.RFC__c, e.Birth_Date__c, e.Plan__c,Product__c from Enrollee__c e where Cve_tipo_registro__c = \'Elegibilidad\' and Enrollee_Status__c = \'Elegible\' and Product__c = \'' + producto + '\'' + strCredencial + strCertificado + strRfc + strPoliza + fNacimiento + nombres + Contratante + Aseguradora;
System.debug(':::: query concatenado = ' + query);
lMSD = Database.query(query);
cuentacriterios = 0;
} else {
System.debug(':::: Sin criterios');
bLista = false;
correcto = false;
cuentacriterios = 0;
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,'Debe filtrar al menos por dos criterios.'));
}
if(lMSD.size() == 0 && correcto == true) {
bLista = false;
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.INFO,'No se obtuvieron resultados basado en sus criterios de búsqueda. Utilice un criterio diferente o comuníquese al Centro de Contacto para confirmar elegibilidad.'));
msd = new Enrollee__c();
}
if(lMSD.size() > 0) {
ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.CONFIRM,'Se encontraron ' + lMSD.size() + ' registros. Favor de seleccionar el registro que corresponda con el nombre de su paciente.'));
msd = new Enrollee__c();
}
here is My test Class
private static void cargaPacientesTesting(){
Test.startTest();
PortalProveedoresController obj = new PortalProveedoresController();
obj.cargaPacientes();
Test.stopTest();
}
Thank you Im stuck with this, thanks

PIVOT Perfomance is very slow in SQL

I have attached one sample.This is like query method.But i am using this query in stored procedure .Query is very fast.But in procedure very slow.What is the reason.
DECLARE #lsId VARCHAR(20);
DECLARE #lsDate VARCHAR(20);
SET #lsId = '802306';
SET #lsDate = '2017-10-02';
SELECT fld_region [REGION],
ISNULL([CINEMA], 0) [CINEMA],
ISNULL([ECONOMY], 0) [ECONOMY],
ISNULL([HD PRIME], 0) [HD PRIME],
ISNULL([HD SUPREME], 0) [HD SUPREME],
ISNULL([HD ULTRA], 0) [HD ULTRA],
ISNULL([INDI], 0) [INDI],
ISNULL([KUSHI], 0) [KUSHI],
ISNULL([MEGA], 0) [MEGA],
ISNULL([ROI VALUE], 0) [ROI VALUE],
ISNULL([ROI VALUE PLUS], 0) [ROI VALUE PLUS],
ISNULL([SOUTH VALUE], 0) [SOUTH VALUE],
ISNULL([SUPER VALUE], 0) [SUPER VALUE],
ISNULL([WORLD], 0) [WORLD]
FROM
(
SELECT b.fld_region,
a.fld_pack_name,
a.fld_count
FROM TBL_ACTIVE_CUSTOMER_DT_PLAN_WISE a
JOIN VHierarchyDT b ON b.FLD_DTCODE = a.FLD_DTCODE
AND b.SH_ID = #lsId
AND a.fld_act_date = #lsDate
) x PIVOT(SUM(fld_count) FOR fld_pack_name IN([CINEMA],
[ECONOMY],
[HD PRIME],
[HD SUPREME],
[HD ULTRA],
[INDI],
[KUSHI],
[MEGA],
[ROI VALUE],
[ROI VALUE PLUS],
[SOUTH VALUE],
[SUPER VALUE],
[WORLD])) p;
Maybe try setting the variable datatypes
DECLARE #lsId INT; --If this is the correct data type
DECLARE #lsDate DATE; --If this is the correct data type
SET #lsId = 802306;
SET #lsDate = '2017-10-02';
SELECT fld_region [REGION],
ISNULL([CINEMA], 0) [CINEMA],
ISNULL([ECONOMY], 0) [ECONOMY],
ISNULL([HD PRIME], 0) [HD PRIME],
ISNULL([HD SUPREME], 0) [HD SUPREME],
ISNULL([HD ULTRA], 0) [HD ULTRA],
ISNULL([INDI], 0) [INDI],
ISNULL([KUSHI], 0) [KUSHI],
ISNULL([MEGA], 0) [MEGA],
ISNULL([ROI VALUE], 0) [ROI VALUE],
ISNULL([ROI VALUE PLUS], 0) [ROI VALUE PLUS],
ISNULL([SOUTH VALUE], 0) [SOUTH VALUE],
ISNULL([SUPER VALUE], 0) [SUPER VALUE],
ISNULL([WORLD], 0) [WORLD]
FROM
(
SELECT b.fld_region,
a.fld_pack_name,
a.fld_count
FROM TBL_ACTIVE_CUSTOMER_DT_PLAN_WISE a
JOIN VHierarchyDT b ON b.FLD_DTCODE = a.FLD_DTCODE
AND b.SH_ID = #lsId
AND a.fld_act_date = #lsDate
) x PIVOT(SUM(fld_count) FOR fld_pack_name IN([CINEMA],
[ECONOMY],
[HD PRIME],
[HD SUPREME],
[HD ULTRA],
[INDI],
[KUSHI],
[MEGA],
[ROI VALUE],
[ROI VALUE PLUS],
[SOUTH VALUE],
[SUPER VALUE],
[WORLD])) p;
OR Pulling initial data into a temporary table
DECLARE #lsId INT; --If this is the correct data type
DECLARE #lsDate DATE; --If this is the correct data type
SET #lsId = 802306;
SET #lsDate = '2017-10-02';
IF OBJECT_ID('tempdb..##PivotData') IS NOT NULL
DROP TABLE ##PivotData
SELECT b.fld_region,
a.fld_pack_name,
a.fld_count
INTO ##PivotData --I would normally create and not select into.
FROM TBL_ACTIVE_CUSTOMER_DT_PLAN_WISE a
JOIN VHierarchyDT b ON b.FLD_DTCODE = a.FLD_DTCODE
AND b.SH_ID = #lsId
AND a.fld_act_date = #lsDate
SELECT fld_region [REGION],
ISNULL([CINEMA], 0) [CINEMA],
ISNULL([ECONOMY], 0) [ECONOMY],
ISNULL([HD PRIME], 0) [HD PRIME],
ISNULL([HD SUPREME], 0) [HD SUPREME],
ISNULL([HD ULTRA], 0) [HD ULTRA],
ISNULL([INDI], 0) [INDI],
ISNULL([KUSHI], 0) [KUSHI],
ISNULL([MEGA], 0) [MEGA],
ISNULL([ROI VALUE], 0) [ROI VALUE],
ISNULL([ROI VALUE PLUS], 0) [ROI VALUE PLUS],
ISNULL([SOUTH VALUE], 0) [SOUTH VALUE],
ISNULL([SUPER VALUE], 0) [SUPER VALUE],
ISNULL([WORLD], 0) [WORLD]
FROM ##PivotData x
PIVOT(SUM(fld_count) FOR fld_pack_name IN([CINEMA],
[ECONOMY],
[HD PRIME],
[HD SUPREME],
[HD ULTRA],
[INDI],
[KUSHI],
[MEGA],
[ROI VALUE],
[ROI VALUE PLUS],
[SOUTH VALUE],
[SUPER VALUE],
[WORLD])) p;

'NoneType' object is not subscriptable in using django smart selects

from django.db import models
from django.core.urlresolvers import reverse
from django.utils import timezone
from smart_selects.db_fields import ChainedForeignKey, ChainedManyToManyField, GroupedForeignKey
# Create your models here.
#DIRECTOR
class director(models.Model):
sex = (
('M', 'Male'),
('F', 'Female'),
)
percent = (
('1', 1),
('2', 2),
('3', 3),
)
stats = (
('Single', 'Single'),
('Married', 'Maried'),
('Separated', 'Separated'),
('Widowed', 'Widowed'),
)
firstname = models.CharField(max_length=30, blank = False)
lastname = models.CharField(max_length=30, blank = False)
middlename = models.CharField(max_length=30, blank = True)
birthdate = models.DateField(blank = False)
age = models.IntegerField(blank = False)
contact = models.CharField(blank = False, max_length=11, default="")
email = models.CharField(blank = False, max_length=30, default="")
civil_status = models.CharField(max_length=20, default="", choices = stats, blank = False)
gender = models.CharField(max_length=1, choices = sex, blank = False)
lot_no = models.CharField(max_length=10, blank = False)
block_no = models.CharField(max_length=20, blank = False)
street = models.CharField(max_length=20, blank = False)
brgy = models.CharField(max_length=30, blank =False, default="")
city = models.CharField(max_length=30, blank = False)
region = models.CharField(max_length=50, blank = False)
commission = models.CharField(max_length=1, choices = percent)
#def get_absolute_url(self):
# return reverse('viewname', kwargs={'pk': self.pk})
def __str__(self):
return self.firstname + ' ' + self.middlename + ' ' + self.lastname
#MANAGER
class manager(models.Model):
sex = (
('M', 'Male'),
('F', 'Female'),
)
percent = (
('1', 1),
('2', 2),
('3', 3),
)
stats = (
('Single', 'Single'),
('Married', 'Maried'),
('Separated', 'Separated'),
('Widowed', 'Widowed'),
)
director_name = models.ForeignKey(director)
firstname = models.CharField(max_length=30, blank = False)
lastname = models.CharField(max_length=30, blank = False)
middlename = models.CharField(max_length=30, blank = True)
birthdate = models.DateField(blank = False)
age = models.IntegerField(blank = False)
contact = models.CharField(blank = False, max_length=11, default="")
email = models.CharField(blank = False, max_length=30, default="")
civil_status = models.CharField(max_length=10, default="", choices = stats, blank = False)
gender = models.CharField(max_length=1, choices = sex, blank = False)
lot_no = models.CharField(max_length=20, blank = False)
block_no = models.CharField(max_length=10, blank = False)
street = models.CharField(max_length=20, blank = False)
brgy = models.CharField(max_length=30, blank =False, default="")
city = models.CharField(max_length=30, blank = False)
region = models.CharField(max_length=50, blank = False)
commission = models.CharField(max_length=1, choices = percent, blank = False)
def __str__(self):
return self.firstname + ' ' + self.middlename + ' ' + self.lastname
'''return "%s (%s)" % (
self.firstname + ' ' + self.middlename + ' ' + self.lastname,
", ".join(director.firstname + ' ' + director.middlename + ' ' + director.lastname for director in self.director_name.all())
)'''
#ASSOCIATE
class associate(models.Model):
sex = (
('M', 'Male'),
('F', 'Female'),
)
percent = (
('1', 1),
('2', 2),
('3', 3),
)
stats = (
('Single', 'Single'),
('Married', 'Maried'),
('Separated', 'Separated'),
('Widowed', 'Widowed'),
)
#area = ChainedForeignKey(Area, chained_field="country", chained_model_field="country")
director_name = models.ForeignKey(director)
#manager_name = models.ForeignKey(manager, blank = False)
manager_name = ChainedForeignKey(
manager,
chained_field="director_name",
chained_model_field="director_name",
show_all=False,
auto_choose=True
)
firstname = models.CharField(max_length=30, blank = False)
lastname = models.CharField(max_length=30, blank = False)
middlename = models.CharField(max_length=30, blank = True)
birthdate = models.DateField(blank = False)
age = models.IntegerField(blank = False)
contact = models.CharField(blank = False, max_length=11, default="")
email = models.CharField(blank = False, max_length=30, default="")
civil_status = models.CharField(max_length=20, default="", choices = stats, blank = False)
gender = models.CharField(max_length=1, choices = sex, blank = False)
lot_no = models.CharField(max_length=10, blank = False)
block_no = models.CharField(max_length=20, blank = False)
street = models.CharField(max_length=20, blank = False)
brgy = models.CharField(max_length=30, blank =False, default="")
city = models.CharField(max_length=30, blank = False)
region = models.CharField(max_length=50, blank = False)
commission = models.CharField(max_length=1, choices = percent, blank = False)
def __str__(self):
#return self.firstname + ' ' + self.middlename + ' ' + self.lastname
return "%s (%s)" % (
self.firstname + ' ' + self.middlename + ' ' + self.lastname,
", ".join(director.firstname + ' ' + director.middlename + ' ' + director.lastname for director in self.director_name.all()),
", ".join(manager.firstname + ' ' + manager.middlename + ' ' + manager.lastname for manager in self.manager_name.all()),
)
enter image description here

Reversing numbers in C without using built in reverse function

I've been given a problem in class and to solve it I can't use the built in functions that already exist in c. It has to be an algorithm that performs the action. My function is below:
int reverseDigits(int userNumber)
{
int rev1, rev2, rev3, rev4, reverseNumber;
rev1 = userNumber/1000;
rev2 = (userNumber - (rev1 * 1000)) / 100;
rev3 = (userNumber - ((rev1 * 1000) + ( rev2 * 100))) / 10;
rev4 = (userNumber - ((rev1 *1000) + (rev2 * 100) + (rev3 * 10))) / 1;
if (rev1 == 0 && rev2 >= 1)
{
reverseNumber = ((rev2 *100) + (rev3 *10) + (rev1 * 1));
return reverseNumber;
}
else if (rev2 == 0 && rev3 >= 1)
{
reverseNumber = ((rev3 * 10) + (rev1 * 1));
}
else if (rev3 == 0 && rev4 >= 1)
{
reverseNumber = (rev4 * 1);
}
else
{
reverseNumber = ((rev4 * 1000) + (rev3 * 100) + (rev2 * 10) + (rev1 * 1));
return reverseNumber;
}
}
The function gets a user input and reverses it. My problem is that when given any number with less than 4 digits (It's only supposed to receive 4) the function returns them correctly but it adds zeros. For instance I send it 678 it will return 8760 or 57 would be 7500. Thanks for any help.
This will work up to 9 digits.
int reverse(int num)
{
int res = 0, tmp;
while(num != 0)
{
tmp = num % 10;
res = res*10 + tmp;
num /= 10;
}
return res;
}
The problem is in the invalid set of if-else statements.
Using your approach the program can look like
#include <stdio.h>
int reverseDigits( int userNumber )
{
int rev1, rev2, rev3, rev4, reverseNumber;
rev1 = userNumber / 1000;
rev2 = ( userNumber - ( rev1 * 1000 ) ) / 100;
rev3 = ( userNumber - ( ( rev1 * 1000 ) + ( rev2 * 100 ) ) ) / 10;
rev4 = ( userNumber - ( ( rev1 * 1000 ) + ( rev2 * 100 ) + ( rev3 * 10 ) ) ) / 1;
if ( rev1 != 0 )
{
reverseNumber = ( rev1 * 1 ) + ( rev2 * 10 ) + ( rev3 * 100 ) + ( rev4 * 1000 );
}
else if ( rev2 != 0 )
{
reverseNumber = ( rev2 * 1 ) + ( rev3 * 10 ) + ( rev4 * 100 );
}
else if ( rev3 != 0 )
{
reverseNumber = ( rev3 * 1 ) + ( rev4 * 10 );
}
else
{
reverseNumber = ( rev4 * 1 );
}
return reverseNumber;
}
int main( void )
{
for ( unsigned int x = 0, n = 1000; n != 0; n /= 10 )
{
x += n;
printf( "%d\t%d\n", x, reverseDigits( x ) );
}
return 0;
}
Its output is
1000 1
1100 11
1110 111
1111 1111
This should do:
int main()
{
int num,i=0;
scanf("%d",&num);
int digit[4]={0};
int num_digits=0;
while(num!=0)
{
digit[num_digits] = num%10;
num = num/10;
num_digits++;
}
for(i=0;i<num_digits;i++)
{
printf("%d",digit[i]);
}
return 0;
}
This can help you edit any number, with any number of digits. Just increase the array size of digit.
Edit :Iterator mistaked edited.
Errors in posted code
The computation under the first if clause is wrong. Instead of
reverseNumber = ((rev2 *100) + (rev3 *10) + (rev1 * 1));
it needs to be
reverseNumber = ((rev4 *100) + (rev3 *10) + (rev2 * 1));
The computation under the first else if clause is wrong. Instead of
reverseNumber = ((rev3 * 10) + (rev1 * 1));
it needs to be
reverseNumber = ((rev4 * 10) + (rev3 * 1));
You are missing return statements in the two else if clauses. As a consequence, if your program gets into those clauses, no return statement is executed and the program has undefined behavior. You can resolve that by removing the return statements you have now and adding a return statement at the end.
if (rev1 == 0 && rev2 >= 1)
{
reverseNumber = ((rev4 *100) + (rev3 *10) + (rev2 * 1));
}
else if (rev2 == 0 && rev3 >= 1)
{
reverseNumber = ((rev4 * 10) + (rev3 * 1));
}
else if (rev3 == 0 && rev4 >= 1)
{
reverseNumber = (rev4 * 1);
}
else
{
reverseNumber = ((rev4 * 1000) + (rev3 * 100) + (rev2 * 10) + (rev1 * 1));
}
return reverseNumber;
A recursive solution
If you are able to use recursive functions, you can use:
int reverseDigits2(int userNumber, int res)
{
if ( userNumber == 0 )
{
return res;
}
return reverseDigits2(userNumber/10, 10*res + (userNumber%10));
}
int reverseDigits(int userNumber)
{
return reverseDigits2(userNumber, 0);
}

SQLServerException Invalid column name

I have a problem that doesn't appear always, but it do it most of the times. In my huge java forecast class I have some ResultSets, and when I execute the routine I get:
com.microsoft.sqlserver.jdbc.SQLServerException: El nombre de columna DistanciaMision no es vßlido.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:170)
at com.microsoft.sqlserver.jdbc.SQLServerResultSet.findColumn(SQLServerResultSet.java:626)
at com.microsoft.sqlserver.jdbc.SQLServerResultSet.getString(SQLServerResultSet.java:2301)
at es.csic.iiia.udt.itim.iInformation.WebData.Forecast.etaMSR(Forecast.java:1109)
at es.csic.iiia.udt.itim.iInformation.WebData.Forecast.phase2(Forecast.java:662)
at es.csic.iiia.udt.itim.iInformation.WebData.Forecast.setData(Forecast.java:166)
at es.csic.iiia.udt.itim.iInformation.WebData.Forecast.main(Forecast.java:81)
at es.csic.iiia.udt.itim.iInformation.WebData.Forecast.execute(Forecast.java:71)
at org.quartz.core.JobRunShell.run(JobRunShell.java:199)
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:546)
The column exists, so I don't know what is the problem...
The code line is this one:
Float distancia_restante = (float) ( Integer.parseInt(rs.getString("DistanciaMision")) - (myodometer - initialodometer));
The same problem appears on other columns but it usually crash here.
Thank you!
Edit: ok, this is the whole method:
private static void etaMSR() throws Exception, SQLException {
/**
*
* Calculem ETAN MSR - Mision - Seguimiento - Restricciones conductor
*
*
**/
System.out
.print("Get data from iTIM forecast&forecastAUX DDBB ....... ");
myStatement = MSSQLServerAccess.connection();
// Distancia mision, ruta, hora mision anterior, hora
rs = getTable("SELECT dbo.WebForecast.IdConductor, dbo.WebForecast.IdMision, dbo.WebForecast.IdMisionAnterior, dbo.WebForecast.DistanciaMision, "
+ " WebForecast_1.HoraIniMis AS himanterior, dbo.WebForecast.HoraFiMis AS hfmactual, WebForecast_1.Ciudad AS CiudadOrigen,"
+ " dbo.WebForecast.Ciudad AS CiudadDestino, dbo.Distancias.Ruta, dbo.WebForecast.HoraDistancia AS HoraDistancia"
+ " FROM dbo.WebForecast AS WebForecast_1 INNER JOIN"
+ " dbo.Distancias ON WebForecast_1.Ciudad = dbo.Distancias.Origen RIGHT OUTER JOIN"
+ " dbo.WebForecast ON WebForecast_1.IdMision = dbo.WebForecast.IdMisionAnterior AND dbo.Distancias.Destino = dbo.WebForecast.Ciudad"
+ " WHERE (dbo.WebForecast.IdConductor <> '') AND (CONVERT(datetime, '"
+ df.format(fechaDia)
+ "') <= dbo.WebForecast.HoraFiMis) "
+ " AND WebForecast_1.HoraIniMis <= CONVERT(datetime, '"
+ df.format(fechaDia) + "') ");
System.out.println("[ok]");
while (rs.next() && (rs.getString("IdConductor") != "") && org.apache.commons.lang.StringUtils.isNumeric(rs.getString("IdConductor"))) {
int initialodometer = 0;
String start = null;
if (rs.getString("HoraDistancia") != null) {
start = rs.getString("HoraDistancia");
}
if (rs.getString("himanterior") != null) {
start = rs.getString("himanterior");
}
if (start != null) {
ResultSet myrs = null;
Timestamp tobjetivo = rs.getTimestamp("himanterior");
long boundtime = 7200000; // 3600000 = 60m = 1h
Timestamp tini = (Timestamp) rs.getTimestamp("himanterior")
.clone();
Timestamp tfin = (Timestamp) rs.getTimestamp("himanterior")
.clone();
tini.setTime(tini.getTime() - boundtime);
tfin.setTime(tfin.getTime() + boundtime);
int contador = 0;
long bestdiff = 0;
myStatement = MSSQLServerAccess.connection();
myrs = getTable("SELECT DISTINCT Odometer, DT "
+ "FROM DriverEvents "
+ "WHERE (DT BETWEEN CONVERT(datetime, '"
+ df.format(tini) + "') " + "AND CONVERT(datetime, '"
+ df.format(tfin) + "')) " + "AND (CardId = '"
+ Integer.parseInt(rs.getString("IdConductor")) + "')");
int j = 0;
while (!myrs.next() && (j < 20)) {
// En caso de no encontrar en las 2h antes y despues nada:
tini.setTime(tini.getTime() - boundtime);
tfin.setTime(tfin.getTime() + boundtime);
myrs.close();
myStatement = MSSQLServerAccess.connection();
myrs = getTable("SELECT DISTINCT Odometer, DT "
+ "FROM DriverEvents "
+ "WHERE (DT BETWEEN CONVERT(datetime, '"
+ df.format(tini) + "') "
+ "AND CONVERT(datetime, '" + df.format(tfin)
+ "')) " + "AND (CardId = '"
+ Integer.parseInt(rs.getString("IdConductor"))
+ "')");
j++;
}
if (myrs.next()) {
initialodometer = myrs.getInt("Odometer");
bestdiff = Math.abs(tobjetivo.getTime()
- myrs.getTimestamp("DT").getTime());
contador++;
while (myrs.next()) {
long pretendiente = Math.abs(tobjetivo.getTime()
- myrs.getTimestamp("DT").getTime());
if (pretendiente <= bestdiff) {
bestdiff = pretendiente;
initialodometer = myrs.getInt("Odometer");
}
contador++;
}
}
myrs.close();
}
// Get Odometer distance at the moment
if (!rs.getString("IdConductor").isEmpty() && !rs.getString("IdConductor").equals("") ) {
ResultSet myrs = null;
int myodometer = 0;
myStatement = MSSQLServerAccess.connection();
myrs = getTable("SELECT MAX(DT) AS DT, MAX(Odometer) AS Odometer"
+ " FROM dbo.DriverEvents"
+ " WHERE (CardId = '"
+ Integer.parseInt(rs.getString("IdConductor"))
+ "') AND (DT > CONVERT(datetime, '"
+ df.format(fechaDatos) + "')) ");
if (myrs.next()) {
myodometer = myrs.getInt("Odometer");
if (initialodometer == 0)
initialodometer = myodometer;
Float distancia_restante = (float) ( Integer.parseInt(rs.getString("DistanciaMision")) - (myodometer - initialodometer));
if (distancia_restante < 0)
distancia_restante = (float) 0;
Timestamp ETAN = null;
Calendar cal = Calendar.getInstance();
if (rs.getTimestamp("himanterior") != null && rs.getTimestamp("himanterior").toString() != "") {
cal.setTimeInMillis(rs.getTimestamp("himanterior")
.getTime());
if (cal.after(Calendar.getInstance())) {
cal.setTimeInMillis(rs.getTimestamp("himanterior")
.getTime());
}
if (cal.before(Calendar.getInstance())) {
cal = Calendar.getInstance();
}
} else {
if (rs.getTimestamp("HoraDistancia") != null)
cal.setTimeInMillis(rs
.getTimestamp("HoraDistancia").getTime());
}
myStatement = MSSQLServerAccess.connection();
rs2 = getTable("SELECT TOP (100) PERCENT CardId, DT"
+ " FROM dbo.DriverEvents"
+ " GROUP BY CardId, DT"
+ " HAVING (CardId = '"
+ Integer.parseInt(rs.getString("IdConductor"))
+ "') AND (DT > CONVERT(datetime, '"
+ df.format(fechaDatos) + "'))");
if (rs2.next()) {
ETAN = getETAN(rs, distancia_restante, cal);
} else {
ETAN = getETA(rs, distancia_restante, cal, 1);
Statement myStatement2 = MSSQLServerAccess.connection();
myStatement2.executeUpdate("UPDATE WebForecast "
+ "SET ETAmsr = '" + df.format(ETAN)
+ "', KmsDiff = '" + distancia_restante.intValue()
+ "' " + "WHERE IdMision = '"
+ rs.getString("IdMision") + "'");
} else {
}
}
}
rs.close();
}
And the statement, maybe i'm doing something wrong?:
private static Statement conStatement(Properties properties){
String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; // Load the JDBC driver
String dbURL = "jdbc:sqlserver://"
+ properties.getProperty("qualcomm.action.JDBC.MSSQLServerAccess.ddbbserverIP")
+ ";DatabaseName="
+ properties.getProperty("qualcomm.action.JDBC.MSSQLServerAccess.ddbbName")
+ ";SelectMethod=Cursor;"; // Connect to a server and database
String userName = properties.getProperty("qualcomm.action.JDBC.MSSQLServerAccess.userName");
String userPwd = properties.getProperty("qualcomm.action.JDBC.MSSQLServerAccess.userPwd");
Connection dbConn;
try {
Class.forName(driverName);
dbConn = DriverManager.getConnection(dbURL, userName, userPwd);
//log.info("Connection Successful!");
Statement myst = dbConn.createStatement();
return myst;
} catch (Exception e) {
log.error(e);
System.out.println(e);
return null;
}
}
Thanks guys :) Could be something wrong with the statement?
remember that Java is case-sensitive and so can be your table on SQL depending on the way you created them, actually depending on the collation on your DB. If your database is created with a Case Sensitive collation then all object names will be Case Sensitive.
try to check the exact columns name of the column on SQL and access it using [] and the exact case

Resources