mercredi 31 août 2016

Merge with delete nested query not giving delete count

I am trying merge with delete in that I want to take count of records getting deleted I have following snippet

MERGE  @DuplicateCurrencyData  DD USING 
        (SELECT PP.PAYMENTB_ID,PP.PPID,PP.BID FROM ProfileTable PP) tempTable
            ON DD.PPID = tempTable.PPID
            WHEN MATCHED THEN
                    UPDATE SET DD.PBID=tempTable.PAYMENTB_ID 


                    OUTPUT
                    $action, Updated.PBID 'Updated' INTO #MergeCountP;

It gives me error

Msg 4104, Level 16, State 1, Line 122
The multi-part identifier "Updated.PBID" could not be bound.

If I not take count Merge statement works fine , I am unable to understand how take rid of it

Giving alias name with space in sql

I have a column in my query for which I want to use its alias name.

Currently it is looking like this:

SELECT U.first_name + ' ' + U.last_name UserName,

But I want to use it as like below

SELECT U.first_name + ' ' + U.last_name as User Name,

I tried but I got error as:

Incorrect syntax near the keyword 'User'.

sql server - check to see if cast is possible then use in order clauses

I have a varchar(20) column, need to convert to int and use in order clauses. But things is okay when it is possible to convert. My code:

            SELECT    DISTINCT people.ParYear,CAST(people.ParID As int), people.Pfamily, people.Pname
            FROM               people 
                WHERE                        people.osID    = @osID 
                         AND people.shID    = @shID
                         AND people.ParYear = @ParYear
               ORDER BY        people.ParYear, CAST(people.ParID As int)

So how can I avoid error Message like Conversion failed!

How to Backup Database on Database Creation Date?

I have a scenario, On every start of the month new database is dynamically created and we have to take backup of newly created database. Full database backup is not required only backup is required for newly created databases, so how how can I take backup of these newly created databases?

lundi 29 août 2016

Add a security layer to our SQL Servers (currently accesible from remote sql management studio)

We have a big system running with thousands of users (some from android apps, other from the web app, etc.).

The system is distributed, with databases in two locations (within the same country). In one location there are 5 servers in the same network, and each one has a copy of the database (via replication).

Among the software developers, a few have direct access to the production databases. Sometimes due to technical support requested by users to modify some operations not possible from the system itself, the developers/support team have to access the database directly and modify some records.

We know this is not the ideal manner of working. But it's been like this since years.

Recently we have found a few problems. One day one person updated hundreds of records from a table by mistake.

Since then we are analyzing how to improve this access.

We are looking for some way of improving the security. We would like to have a two-phase authentication system in place. Something that asks the user for two passwords when accessing from Sql Server Management Studio...

Is that possible? Or is there any other approach we can use to improve the security but still allow devs/support team to access the production database when necessary?

Users also (currenty) have access via remote desktop to all servers.

At least we would like to KNOW when this access is being done.

samedi 27 août 2016

SQL 2005 : Email Profile that send me email even if removed

I'm having a problem with email service for SQL 2005. When i set my first backup maintenance plan, I've activated a mail that notify me if the backup was complete successfull. Then I've removed the mail alert but, I'm still receveing the email from the agent... How can I solve that?

vendredi 26 août 2016

Combining column name is giving error

I have two columns which I want to combine and show the data, I tried like below

select case when status='R' then 'Resign'
 when status='A' then 'Active' end as status1, 
  Program_name + ' ' + emp_card_no as program_details,
   * from GetEmployeeDetails
  Where emp_name ='ABHAY ASHOK MANE'and STATUS= 'A' ORDER BY EMP_NAME

but I am getting error as

Error converting data type varchar to numeric.

here is the sample data available

img

jeudi 25 août 2016

MS SQL error selecting count on a subquery

I am trying to select the count of the number of rows returned on a query. The query is

Select a.itm_cd, max(b.doc_num) ,max(c.text) 
from ist b,itm_trn a, ist_cmnt c  
where a.ist_seq_num = b.ist_seq_num 
and a.ist_seq_num = c.ist_seq_num  
and a.ist_wr_dt = b.ist_wr_dt 
and a.new_loc_cd  like 'BOX115' 
and a.ITT_CD = 'XFR' and a.create_dt >'21-AUG-16' 
group by a.itm_cd;

For this particular query I return 3 rows, I need to write a query that returns how many rows are returned.

I have tried this :

Select count(*) from 
(Select a.itm_cd, max(b.doc_num) ,max(c.text) 
from ist b,itm_trn a, ist_cmnt c  
where a.ist_seq_num = b.ist_seq_num 
and a.ist_seq_num = c.ist_seq_num  
and a.ist_wr_dt = b.ist_wr_dt 
and a.new_loc_cd  like 'BOX115' 
and a.ITT_CD = 'XFR' and a.create_dt >'21-AUG-16' 
group by a.itm_cd);

This results in a syntax error

msg 102, level 15, state 1 line 1  incorrect syntax near ')'.

I am not sure what I am doing wrong, I have a similar sql statement that works this way in oracle, but have not found where I am messing up in MSSQL

mercredi 24 août 2016

Enabling AES_128_CBC and RC4_128 for JDBC connections to MS SQL Server 2005

To ensure backward compatibility of my application, I'm testing JDBC over TLS behaviour when an MS SQL Server version vulnerable to CVE-2011-3389 is used (any 2005, or 2008/2008R2 w/o service packs fit). In theory, two options are available:

  • either disable CBC protection via -Djsse.enableCBCProtection=false and continue to use a block cipher such as AES_128_CBC or 3DES_EDE_CBC,
  • or fall back to a stream cipher such as RC4 (yes I'm aware this is insecure, too, due to CVE-2015-2808).

In practice, while I have no trouble establishing a connection using 3DES_EDE_CBC with CBC protection off, I'm still unable to use RC4_128 using an JDK newer than 1.8.0_51 (which happened to address CVE-2015-2808) or AES_{128,256}_CBC (using any 1.6+ JDK).

Here's the results broken down by Java version:

  • 1.6.0_45 (jTDS)
    • SSL_RSA_WITH_RC4_128_MD5 is used
  • 1.7.0_76 (jTDS) and 1.8.0_40 (MS SQL JDBC):
    • SSL_RSA_WITH_RC4_128_MD5 (default) or SSL_RSA_WITH_3DES_EDE_CBC_SHA can be used
    • won't use AES_128_CBC even if 3DES is disabled (3DES_EDE_CBC will be forced anyway)
  • 1.8.0_45 (IBM J9 8.0 SR1) (MS SQL JDBC)
    • SSL_RSA_WITH_3DES_EDE_CBC_SHA is used (successful only if CBC protection is off), also if either AES or RC4 is requested
  • 1.8.0_92 (Oracle) (MS SQL JDBC)
    • SSL_RSA_WITH_3DES_EDE_CBC_SHA is used (successful only if CBC protection is off),
    • won't use AES_128_CBC or AES_256_CBC even if requested (unlike previous Java versions, 3DES is no longer forced, instead I get an IOException after ClientHello, which does list *_WITH_AES_128_CBC_SHA as compatible ciphersuites)
    • won't use RC4 even if both with AES and 3DES are disabled: "no negotiable cipher suite" (both jTDS and MS SQL JDBC).

Here's the java.security I use to request AES:

jdk.certpath.disabledAlgorithms=MD2
jdk.tls.disabledAlgorithms=SSLv3, RC4, TLSv1.1, TLSv1.2, 3DES_EDE_CBC
jdk.tls.legacyAlgorithms= \
        K_NULL, C_NULL, M_NULL, \
        RC4_128, RC4_40

and here's the version to request RC4:

jdk.certpath.disabledAlgorithms=MD2
jdk.tls.disabledAlgorithms=SSLv3, AES_128_CBC, TLSv1.1, TLSv1.2, AES_256_CBC, AES_128_GCM, AES_256_GCM, 3DES_EDE_CBC
jdk.tls.legacyAlgorithms= \
        K_NULL, C_NULL, M_NULL

Questions:

  • Apparently, AES_{128,256}_CBC is supported by my Java clients, as I can use TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA when connecting to MS SQL Server 2014. Can anyone confirm it is not supported by MS SQL Server 2005? Since disabling AES effectively leads to "no negotiable cipher suite", I assume it is supported, but something happens server-side, even though CBC protection is off.
  • How can I still use RC4 in Java 1.8.0_51+? This solution no longer works, nor has any effect https.cipherSuites system property (described here). There's a magical jdk.tls.enableRC4CipherSuites system property in 6u115 and 7u101, but it seems to have no effect in Java 1.8.
  • What the heck is wrong with jTDS? It works fine with Java 1.6 and 1.7 (driver versions 1.2.8 and 1.3.1), but using Java 1.8 I'm constantly receiving "Connection reset by peer" whenever MS SQL JDBC would just use 3DES to encrypt connection data.

How to pass stored procedure's parameter values to temp table using MS SQL 2005?

I need to store the procedures acutal parameter values to a temp table. I tried to create a script which can be applied for different stored procedures, therefore the script cannot contain the name of the parameters. This is the code I made, however when I try to store the value of parameters one by one in a temp table, I get error message saying the parameter have to be declared. Please help how to solve this one.

ALTER PROCEDURE [dbo].[EQSP_Parameters] (@MIC varchar(4), @ISIN varchar(12), @Client varchar(12), @TradeDate datetime, @Email int )

mardi 23 août 2016

Make mssql query

help me please with query:
select * from sc84 as nom join sc319 as p on p.PARENTEXT = nom.id join sc219 as pt on p.sp327 = pt.id join _1SCONST as c on c.objid=p.id
As a result approximately such table
Car / price_base / 08-08-2016:13-40 / 100 /
Car / price_base / 08-08-2016:14-40 / 150 /
Car / price_base / 08-09-2016:13-40 / 190 /
Car / price_super / 08-09-2016:18-40 / 210 /
Car / price_super / 08-10-2016:13-40 / 290 /
That is goods, types of the price of date and their value. Prompt please how to receive the last (the actual price for each type of the price and each goods) tried options with group but there is obviously not enough skill.

nom.id - PK SKU     
pt.id - PK price type   
p.id -PK price    
p.parentext - parent price (sku)    
p.sp327 - FK to price type   
date = date column   

SQL Server 2005 : Create Procedure for Google Directions

Can you help me to convert this procedure that give me the distance beetween the start address and the end address

CREATE PROCEDURE [dbo].[CalculateDistanceGoogle]
    (@ToAddress NVARCHAR(100), 
     @FromAddress NVARCHAR(100), 
     @DistanceistanceInKm FLOAT OUTPUT) 
AS
BEGIN
    SET NOCOUNT ON;

    DECLARE @Object INT 
    DECLARE @ResponseonseText NVARCHAR(MAX) 
    DECLARE @StatuserviceUrl NVARCHAR(500)

    SET @StatuserviceUrl = 'http://ift.tt/2bfUgvP' + @ToAddress + '&destinations=' + @FromAddress +'&mode=driving&language=en-EN&units=metric&key=APIKEY;'

    EXEC sp_OACreate 'MSXML2.XMLHTTP', @Object OUT; EXEC sp_OAMethod @Object, 'open', NULL, 'get', @StatuserviceUrl, 'false' EXEC sp_OAMethod @Object, 'send' EXEC sp_OAMethod @Object, 'responseText', @ResponseonseText OUTPUT

    DECLARE @Response XML

    SET @ResponseonseText = REPLACE(@ResponseonseText, N'encoding="UTF-8"', N'');
    SET @Response = CAST(CAST(@ResponseonseText AS NVARCHAR(MAX)) AS XML)

    DECLARE @Status NVARCHAR(20) 
    DECLARE @Distance NVARCHAR(20)

    SET @Status = @Response.value('(DistanceMatrixResponse/row/element/status)[1]', 'NVARCHAR(20)')

    IF(@Status = 'ZERO_RESULTS') 
        SET @Distance = NULL 
    ELSE 
        SET @Distance = @Response.value('(DistanceMatrixResponse/row/element/distance/value)[1]', 'NVARCHAR(20)')

    SET @DistanceistanceInKm = ROUND(CAST(@Distance AS FLOAT) / 1000, 1)

    PRINT @DistanceistanceInKm

    EXECUTE sp_OADestroy @Object
END

To a procedure that use the direction api instead of the distance with this link

http://ift.tt/2beA0xX KEY

and print all XML end_address in the order that google give me back?

I'm using SQL Server 2005

lundi 22 août 2016

I'm developing a system that will be save on two different database

Hi Guys i just want to ask an alternative solution for my saving problem i'm saving data in two different database mssql and mysql . Mysql is my backups so every time the user will create an entry it they will be save in two database the user encounter a problem. the user added new entry then when they check the data it doesn't save so every time the user will create the same data it will result to duplicate entry because the data was saved firt in mssql then after that it will be saved on mysql any solutions may help thank you so much

SQL and Shipping Optimization

I need to optimize my shipping process. I need to take datas from sql2005 server and then I think to use Google Directions Api to optimize the locations order. But I don't know if it is the best solution to use those api or if there's another service to directly show the result of a query on google maps and then calculate the best road. My query must look to destinations in the next 3 weeks. So I need also to crop this order, selecting for example 3 or 4 location for each day in the next 3 weeks. Can you help me to find the best solution? Thank you!

dimanche 21 août 2016

Procedure result with XML parsing error

Hi guys I'm trying to use my first procedure. I need it for Google Matrix. This is my procedure, found there

CREATE PROCEDURE [dbo].[CalculateDistanceGoogle] ( @ToAddress NVARCHAR(100) , @FromAddress NVARCHAR(100), @DistanceistanceInKm FLOAT OUTPUT ) AS

BEGIN

DECLARE @Object INT DECLARE @ResponseonseText NVARCHAR(4000) DECLARE @StatuserviceUrl NVARCHAR(500)

SET @StatuserviceUrl = 'http://ift.tt/19WUt3A' + @ToAddress + '&destinations=' + @FromAddress +'&mode=driving&language=it-IT&units=metric;'

EXEC sp_OACreate 'MSXML2.XMLHTTP', @Object OUT; EXEC sp_OAMethod @Object, 'open', NULL, 'get', @StatuserviceUrl, 'false' EXEC sp_OAMethod @Object, 'send' EXEC sp_OAMethod @Object, 'responseText', @ResponseonseText OUTPUT

DECLARE @Response XML

SET @Response = CAST(CAST(@ResponseonseText AS NVARCHAR(MAX)) AS XML)

DECLARE @Status NVARCHAR(20) DECLARE @Distance NVARCHAR(20)

SET @Status = @Response.value('(DistanceMatrixResponse/row/element/status)[1]', 'NVARCHAR(20)')

IF(@Status = 'ZERO_RESULTS') SET @Distance = NULL ELSE SET @Distance = @Response.value('(DistanceMatrixResponse/row/element/distance/value)[1]', 'NVARCHAR(20)')

SET @DistanceistanceInKm = ROUND(CAST(@Distance AS FLOAT) / 1000, 1)

PRINT @DistanceistanceInKm

END

And this is the execution to store result of distance in the variable:

DECLARE @Distanza NVARCHAR 
EXEC @Distanza = dbo.CalculateDistanceGoogle @ToAddress = 'CITY', @FromAddress='CITY',  @DistanceistanceInKm = @Distanza
PRINT @Distanza

I've this error:

Msg 9402, Level 16, State 1, Procedure CalculateDistanceGoogle, Line 13 XML parsing: line 1, character 38, unable to switch the encoding

Can you help me to understand why?

Thank you!

How to named CSV file as yesterday' date?

I need a SQL job to run every day.

This CSV file needs to be named with yesterday’s date. So, if this job was to run today, it would generate a file called 20160820_invoices.csv.

I use following code but it's not work. "C:\Invoices_" + (DT_WSTR,4)DATEPART("yyyy",GetDate()) + RIGHT("0" + (DT_WSTR,2)DATEPART("mm",GetDate()) ,2) + RIGHT("0" + (DT_WSTR,2)DATEADD("dd", -1, GetDate()),2) + ".csv"`

Is there any other way it can get work?

Advice to create a little script to associate near shipping address in the next 3 weeks

Hi guys I'm searching an advice on how to proceed to create a script that can calculate the distance between all shipping address in the next 3 weeks and if the distance between some of these locations is under 50 km it must send an email to make that thing notice to the operator. I'm starting from sql 2005 to take location and make all combination. Then I was thinking if there is some online service that, with a link structure where I can put the two location name, can retrieve the distance between those two point, then store it in different variable to use to make comparisons. I'll wait for some advice.thank you guys

samedi 20 août 2016

Sql 2005: Help to concatenate Nvarchar and Int

I've this block of code with an error because i'm using an Int variable inside a Nvarchar.

 DECLARE @FattAnnoCorrente INT;
DECLARE @Tabscontianno1 NVARCHAR(MAX);

 SET @Tabscontianno1 = 
N'<p align="left"><b>ANNO ' + @Anno1 + ' - </b><b>' + @FattAnnoCorrente + '<br>
  </b></p>
<table height="62" border="1" cellpadding="2" cellspacing="2"
  width="501">
  <tbody>
    <tr>
      <td valign="top">FATTURATO<br>
      </td>
      <td valign="top">SCONTO<br>
      </td>
    </tr>' + CAST ((
                    SELECT  
                    td = SUM(TOTNETTORIGA),    '',
                    td = SCONTIESTESI
                    FROM .dbo.TESTEDOCUMENTI 
                    INNER JOIN .dbo.RIGHEDOCUMENTI
                    ON PROGRESSIVO=IDTESTA AND TOTNETTORIGA <>'0'
                    WHERE  CODCLIFOR = @CodiceCliente AND .dbo.TESTEDOCUMENTI.DOCCHIUSO = '0' AND .dbo.TESTEDOCUMENTI.BLOCCATO = '0' AND .dbo.TESTEDOCUMENTI.TIPODOC = 'FVC'  AND .dbo.TESTEDOCUMENTI.ESERCIZIO = YEAR(GETDATE())
                    GROUP BY TESTEDOCUMENTI.ESERCIZIO,SCONTIESTESI
    FOR XML PATH('tr'), TYPE )
    AS NVARCHAR(MAX) ) +
    N'  </tbody>
</table>'+
    N'<BR/>' ;

I've this error:

Conversion failed when converting the nvarchar value 'ANNO 2016 - ' to data type int.

If I use

CAST(CAST(COALESCE(@FattAnnoCorrente) as int) as varchar(255))

I've instead those errors:

Msg 102, Level 15, State 1, Line 154 Incorrect syntax near ')'. Msg 156, Level 15, State 1, Line 173 Incorrect syntax near the keyword 'FOR'.

Can you help me to solve this problem. After insert it in the nvarchar variable I need to format it as money like that:

'€ ' + REPLACE(CONVERT(varchar, CAST(@FattAnnoCorrente AS money), 105),',','.')

Thank you guys!

vendredi 19 août 2016

Using two cursors in a stored procedure

I have a SP in which there is a cursor which loops and gives me the desired result.

Now what I want is, I want to use the same cursor twice so that the same record should get inserted into the inward_doc_tracking_trl twice

Here is my SP:-

ALTER procedure set_auto_action_1    
                    as       
                   begin 
                declare @inv_hdr_mkey int    
                declare @inv_trl_mkey nvarchar(200)    
                declare @entry_sr_no nvarchar(200)    
                declare @Nuser_mkey varchar(10)    
                declare @n_department varchar(10)    
                declare @cstatus_flag int    
                declare @remarks varchar(500)    
                declare @cuserid int    
                declare @u_datetime DATETIME    
                declare @nstatus_flag int    
                declare @delete_flag varchar(1)    
                declare @cdept_id int    
                declare @ref_mkey int    
                declare @No_Of_Days varchar(10)    
                declare @Approved_Amount numeric(18, 2)    
                declare @Chq_No varchar(10)    
                declare @Chq_dated DATETIME    
                declare @Chq_Bank varchar(10)    
                declare @Chq_Amount numeric(18, 2)    
                declare @Vendor_MKey varchar(10)    
                declare @Vendor_Comp_Mkey varchar(10)    
                declare @Project_Mkey varchar(10)    
                declare @Program_mkey varchar(10)    
                declare @Payment_MKey varchar(10)    
                declare @Due_Date datetime    
                declare @Updated_Remarks varchar(100)    
                declare @Updated_Bill_no varchar(10)    
                declare @Updated_Bill_Date datetime    
                declare @Updated_Bill_Amt numeric(18, 2)    
                declare @Party_Name varchar(100)    
                declare @Acc_mkey varchar(10)    
                declare @TotalDeductions numeric(18, 2)    
                declare @Broker_Mkey varchar(10)    
                declare @Customer_Mkey varchar(10)    
                declare @Payable_Amt numeric(18, 2)    
                declare @Balance_Amt numeric(18, 2)    
                set @Nuser_mkey = NULL    
                set @n_department = NULL    
                set @remarks = 'Document received'    
                set @u_datetime = getdate()    
                set @nstatus_flag=1
                set @cstatus_flag = 2    
                set @delete_flag = 'N'    
                set @No_Of_Days = NULL    
                set @Acc_mkey = NULL          

                declare acCur cursor for select 

                    mkey,status_flag,to_department,to_user,approved_amount,chq_no,chq_dated,chq_bank,chq_amount,vendor_mkey,
                    Vendor_Comp_Mkey,project_mkey,program_mkey,payment_mkey,due_date,updated_remarks,updated_bill_no,updated_bill_date,
                    updated_bill_amt,party_name,totaldeductions,Broker_Mkey,Customer_Mkey,Payable_Amt,balance_amt 
                    from inward_doc_tracking_hdr where status_flag not in (5,13,14)
                    and doc_date <  CONVERT(DATETIME, CONVERT(VARCHAR(10), GETDATE(), 120) + ' 15:00:00')   

                open acCur    

                FETCH NEXT FROM acCur into  
                                    @inv_hdr_mkey,@cstatus_flag,@cdept_id,@cuserid,@Approved_Amount,
                                    @Chq_No,@Chq_dated,@Chq_Bank,@Chq_Amount,@Vendor_MKey,@Vendor_Comp_Mkey,
                                    @Project_Mkey,@Program_mkey,@Payment_MKey,@Due_Date,@Updated_Remarks,@Updated_Bill_no,
                                    @Updated_Bill_Date,@Updated_Bill_Amt,@Party_Name,@TotalDeductions,@Broker_Mkey,
                                    @Customer_Mkey,@Payable_Amt,@Balance_Amt        

                WHILE @@FETCH_STATUS = 0    
                BEGIN    

                                    select @inv_trl_mkey= max(mkey)+1 from inward_doc_tracking_trl     
                                    select @entry_sr_no = max(entry_sr_no)+1 from inward_doc_tracking_trl where ref_mkey=@inv_hdr_mkey



                                    insert into inward_doc_tracking_trl (Mkey,Entry_Sr_No,N_UserMkey,N_Department,
                                    CStatus_Flag,Remarks,
                                    CUser_ID,                           
                                    U_Datetime,NStatus_Flag,Delete_Flag,CDept_Id,Ref_Mkey,
                                    No_Of_Days,Approved_Amount,Chq_No,Chq_dated,Chq_Bank,Chq_Amount,Vendor_MKey,Vendor_Comp_Mkey,
                                    Project_Mkey,Program_mkey,Payment_MKey,Due_Date,Updated_Remarks,Updated_Bill_no,
                                    Updated_Bill_Date,Updated_Bill_Amt,Party_Name,Acc_mkey,TotalDeductions,Broker_Mkey,Customer_Mkey,
                                    Payable_Amt,Balance_Amt) 

                                    values 
                                    (@inv_trl_mkey,@entry_sr_no,@Nuser_mkey,@n_department,@cstatus_flag,
                                    @remarks,                           
                                    CASE WHEN (@cuserid IS NULL) THEN 0 ELSE @cuserid END,
                                    @u_datetime,@nstatus_flag,@delete_flag,
                                    CASE WHEN (@cdept_id IS NULL) THEN 0 ELSE @cdept_id END,
                                    @inv_hdr_mkey,
                                    @No_Of_Days,@Approved_Amount,@Chq_No,@Chq_dated,@Chq_Bank,@Chq_Amount,@Vendor_MKey,
                                    @Vendor_Comp_Mkey,@Project_Mkey,@Program_mkey,@Payment_MKey,@Due_Date,@Updated_Remarks,
                                    @Updated_Bill_no,@Updated_Bill_Date,@Updated_Bill_Amt,@Party_Name,@Acc_mkey,@TotalDeductions,
                                    @Broker_Mkey,@Customer_Mkey,@Payable_Amt,@Balance_Amt)    


                                    FETCH NEXT FROM acCur into @inv_hdr_mkey,@cstatus_flag,@cdept_id,@cuserid,@Approved_Amount,@Chq_No,
                                    @Chq_dated,@Chq_Bank,@Chq_Amount,@Vendor_MKey,@Vendor_Comp_Mkey,@Project_Mkey,@Program_mkey,@Payment_MKey,
                                    @Due_Date,@Updated_Remarks,@Updated_Bill_no,@Updated_Bill_Date,@Updated_Bill_Amt,@Party_Name,
                                    @TotalDeductions,@Broker_Mkey,@Customer_Mkey,@Payable_Amt,@Balance_Amt

                end    
                            close acCur    
                            deallocate acCur    
                end

kindly help me with how to use the same cursor twice in SP

CASE with IS NULL not working

I want to give column some value if the value is NULL I tried like below

insert into inward_doc_tracking_trl 
    (Mkey,Entry_Sr_No,N_UserMkey,N_Department,CStatus_Flag,Remarks,     
    CUser_Id,
    U_Datetime,NStatus_Flag,Delete_Flag, 
    CDept_Id,
    Ref_Mkey,No_Of_Days,Approved_Amount,Chq_No,Chq_dated,Chq_Bank,Chq_Amount,
    Vendor_MKey,Vendor_Comp_Mkey,Project_Mkey,Program_mkey,Payment_MKey,Due_Date,Updated_Remarks,Updated_Bill_no,
    Updated_Bill_Date,Updated_Bill_Amt,Party_Name,Acc_mkey,
    TotalDeductions,Broker_Mkey,Customer_Mkey,Payable_Amt,Balance_Amt)

     values (@inv_trl_mkey,@entry_sr_no,@Nuser_mkey,@n_department,@nstatus_flag2,@remarks,               
        CASE WHEN (@cuserid IS NULL) THEN 'YES' ELSE 'NO' END AS @cuserid,
    @u_datetime,@nstatus_flag,@delete_flag,     
        CASE WHEN (@cdept_id IS NULL) THEN 'YES' ELSE 'NO' END AS @cdept_id,
    @inv_hdr_mkey,@No_Of_Days,
     @Approved_Amount,@Chq_No,@Chq_dated,
     @Chq_Bank,@Chq_Amount,@Vendor_MKey,@Vendor_Comp_Mkey,@Project_Mkey,@Program_mkey,@Payment_MKey,@Due_Date  
    ,@Updated_Remarks,@Updated_Bill_no,@Updated_Bill_Date,@Updated_Bill_Amt,@Party_Name,
    @Acc_mkey,@TotalDeductions,@Broker_Mkey,@Customer_Mkey,@Payable_Amt,@Balance_Amt)  

but getting error as

Incorrect syntax near the keyword 'AS'.

jeudi 18 août 2016

Insert duplicate record with max + 1 entry_sr_no

I have a SP which returns me the Maximum entry no for respective document no.

Now what I want is, I want to insert the same record in the inward_doc_tracking_trl table with max + 1 entry_sr_no

Let say,

Max_Entry_Srno of doc_no = IW/16/5694 is 3, then while inserting the same in trl table the Max_Entry_Srno should be 4.

Here is my SP

 ALTER procedure set_auto_action  
       as   
        begin         
             select hdr.mkey, hdr.doc_no, MAX(trl.entry_sr_no) as Max_Entry_Srno  
              from inward_doc_tracking_hdr hdr  
               JOIN inward_doc_tracking_trl trl  
             ON(hdr.mkey = trl.ref_mkey)  
              where hdr.status_flag     not in (5,13)   
             and trl.U_Datetime < DATEADD(DAY, -1, GETDATE())       
             GROUP BY hdr.mkey, hdr.doc_no  
       end

Also see the screenshot for the result returned by the SP

Screenshot

The table script of inward_doc_tracking_trl is also below:-

CREATE TABLE [dbo].[Inward_Doc_Tracking_Trl](
[Mkey] [numeric](18, 0) NOT NULL,
[Entry_Sr_No] [numeric](4, 0) NOT NULL,
[N_UserMkey] [numeric](10, 0) NULL,
[N_Department] [numeric](10, 0) NULL,
[CStatus_Flag] [numeric](8, 0) NOT NULL,
[Remarks] [varchar](500) NULL,
[CUser_ID] [numeric](10, 0) NOT NULL,
[U_Datetime] [datetime] NOT NULL,
[NStatus_Flag] [numeric](10, 0) NOT NULL, 
[Delete_Flag] [char](1) NULL,
[CDept_Id] [numeric](10, 0) NOT NULL,
[Ref_Mkey] [numeric](18, 0) NULL,
[No_Of_Days] [int] NULL,
[Approved_Amount] [float] NULL,
[Chq_No] [varchar](50) NULL,
[Chq_dated] [datetime] NULL,
[Chq_Bank] [varchar](40) NULL,
[Chq_Amount] [float] NULL,
[Vendor_MKey] [int] NULL,
[Vendor_Comp_Mkey] [int] NULL,
[Project_Mkey] [numeric](10, 0) NULL,
[Program_mkey] [numeric](10, 0) NULL,
[Payment_MKey] [int] NULL,
[Due_Date] [datetime] NULL,
[Updated_Remarks] [varchar](500) NULL,
[Updated_Bill_no] [varchar](27) NULL,
[Updated_Bill_Date] [datetime] NULL,
[Updated_Bill_Amt] [float] NULL,
[Party_Name] [varchar](80) NULL,
[Acc_mkey] [numeric](10, 0) NULL,
[TotalDeductions] [float] NULL,
[Broker_Mkey] [numeric](10, 0) NULL,
[Customer_Mkey] [numeric](10, 0) NULL,
[Payable_Amt] [float] NULL,
[Balance_Amt] [float] NULL,
[Receipt_No] [varchar](50) NULL,
[Po_No] [varchar](50) NULL,
[Bill_No] [varchar](50) NULL,
[Disp_through] [varchar](50) NULL,
[Disp_Through_Name] [varchar](100) NULL,
[Site_Id] [int] NULL,
   CONSTRAINT [PK_Inward_Doc_Tracking_Trl_1] PRIMARY KEY CLUSTERED 
  (
   [Mkey] ASC,
   [Entry_Sr_No] ASC
  )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY =       OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]

) ON [PRIMARY]

NOTE: The reason behind adding the duplicate row with max+ 1 sr_no is to let user know the document is received by that user

SQL 2005 IF not working fine

I've created an if statement to control if a customer discount is right. I take the sales volume of its previous year, control if it is in the exact range, then if it is not I need to write the right discount to apply. My problem is that this suggested discount is not the right one. I'll show you the code. Before I give a sample customer data.

Discount Applied is 60 % Sales Volume 2016--->€ 13.895.90 Sales Volume 2015 ---> € 25.686.92

This is my query:

DECLARE all variables that i need......
SET @Anno1 = YEAR(GETDATE());
SET @Anno2 = YEAR(DATEADD(year,-1,GETDATE()));
SET @Anno3 = YEAR(DATEADD(year,-2,GETDATE()));
SET @datada = DATEADD(DAY, -15, GETDATE());
SET @dataa = GETDATE();

----- set discount sales volume --- 
SET @40 = '€ '+ REPLACE(CONVERT(varchar, CAST('1500.0000' AS money), 105),',','.');
SET @50 = '€ '+ REPLACE(CONVERT(varchar, CAST('15000.0000' AS money), 105),',','.');
SET @60 = '€ '+ REPLACE(CONVERT(varchar, CAST('150000.0000' AS money), 105),',','.');
SET @70 = '€ '+ REPLACE(CONVERT(varchar, CAST('200000.0000' AS money), 105),',','.');
SET @80 = '€ '+ REPLACE(CONVERT(varchar, CAST('500000.0000' AS money), 105),',','.');

---create cursor---
DECLARE c CURSOR FOR
SELECT DISTINCT
   CODCONTO,
   DSCCONTO1
FROM .dbo.TESTEDOCUMENTI 

WHERE D (.dbo.TESTEDOCUMENTI.TIPODOC = 'PCL' OR .dbo.TESTEDOCUMENTI.TIPODOC = 'ORC' ) AND .dbo.TESTEDOCUMENTI.DATADOC BETWEEN @datada AND @dataa



----take each customer----
OPEN c
FETCH NEXT FROM c INTO @CodiceCliente,@Cliente
--IF @CodiceCliente IS NULL goto finescript;
WHILE @@FETCH_STATUS = 0
    BEGIN

-------------------------------------------------------------------
----------------------set sales volumes to variables---
-------------------------------Current year -----
SET @FattAnnoCorrente = 
(SELECT  '€ '+ REPLACE(CONVERT(varchar, CAST(SUM(TOTIMPONIBILE) AS money), 105),',','.') FROM .dbo.TESTEDOCUMENTI 
WHERE  CODCLIFOR = @CodiceCliente ANDAND .dbo.TESTEDOCUMENTI.TIPODOC = 'FVC'  AND .dbo.TESTEDOCUMENTI.ESERCIZIO = YEAR(GETDATE()));

-------------------------------Previous Year -----
SET @FattAnnoPrecedente = 
(SELECT  '€ '+ REPLACE(CONVERT(varchar, CAST(SUM(TOTIMPONIBILE) AS money), 105),',','.') FROM .dbo.TESTEDOCUMENTI 
WHERE  CODCLIFOR = @CodiceCliente  AND .dbo.TESTEDOCUMENTI.TIPODOC = 'FVC'  AND .dbo.TESTEDOCUMENTI.ESERCIZIO = YEAR(DATEADD(year,-1,GETDATE())));
------------------------------2 Previous years -----
SET @Fatt2AnniPrecedenti = 
(SELECT  '€ '+ REPLACE(CONVERT(varchar, CAST(SUM(TOTIMPONIBILE) AS money), 105),',','.') FROM .dbo.TESTEDOCUMENTI 
WHERE  CODCLIFOR = @CodiceCliente AND .dbo.TESTEDOCUMENTI.TIPODOC = 'FVC'  AND .dbo.TESTEDOCUMENTI.ESERCIZIO = YEAR(DATEADD(year,-2,GETDATE())));

----------- Take the last document discount and set to variable ----- 
SET @Sconto = 
(SELECT DISTINCT MAX(SCONTORIGA)                
FROM .dbo.TESTEDOCUMENTI 
WHERE  SCONTORIGA IS NOT NULL AND CODCLIFOR = @CodiceCliente AND (.dbo.TESTEDOCUMENTI.TIPODOC = 'PCL' OR .dbo.TESTEDOCUMENTI.TIPODOC = 'ORC' ) AND .dbo.TESTEDOCUMENTI.DATADOC BETWEEN @datada AND @dataa);

--------------------------verify condition---THERE IS THE TRUOBLES----
---------------------------PREVIOUS YEAR SALES VOLUME----
IF @FattAnnoCorrente IS NULL SET @FattAnnoCorrente = '0'
IF @FattAnnoPrecedente IS NULL SET @FattAnnoPrecedente = '0'
IF @Fatt2AnniPrecedenti IS NULL SET @Fatt2AnniPrecedenti = '0'
IF @FattAnnoPrecedente = '0' goto fatturatocorrente;

IF (@FattAnnoPrecedente > '0' and @FattAnnoPrecedente < @40) and @Sconto < '40' goto finescript;
IF (@FattAnnoPrecedente > @40 and @FattAnnoPrecedente < @50 ) and (@Sconto > '40' and @Sconto < '50') goto finescript;
IF (@FattAnnoPrecedente > @50 and @FattAnnoPrecedente < @60 ) and (@Sconto > '50' and @Sconto < '60') goto finescript;
IF (@FattAnnoPrecedente > @60 and @FattAnnoPrecedente < @70 ) and (@Sconto > '60' and @Sconto < '70') goto finescript;
IF (@FattAnnoPrecedente > @70 and @FattAnnoPrecedente < @80 ) and (@Sconto > '70' and @Sconto < '80') goto finescript;
IF (@FattAnnoPrecedente > @80 and @FattAnnoPrecedente < '999999999999999999' ) and @Sconto > '80' goto finescript;


------------------------------------FIND THE SUGESTED DISCOUNT ------ THIS IS WRONG

IF ((@FattAnnoPrecedente > '0' and @FattAnnoPrecedente < @40 ))
    SET @ScontoPrevisto = 'inferiore al 40%';
IF ((@FattAnnoPrecedente > @40 and @FattAnnoPrecedente < @50 )  )
    SET @ScontoPrevisto = 'compreso tra 40% e 50%';
IF ((@FattAnnoPrecedente > @50 and @FattAnnoPrecedente < @60 )  )
    SET @ScontoPrevisto = 'compreso tra 50% e 60%';
IF ((@FattAnnoPrecedente > @60 and @FattAnnoPrecedente < @70 ) )
    SET @ScontoPrevisto = 'compreso tra 60% e 70%';
IF ((@FattAnnoPrecedente > @70 and @FattAnnoPrecedente < @80 )  )
    SET @ScontoPrevisto = 'compreso tra 70% e 80%';
IF ((@FattAnnoPrecedente > @80 and @FattAnnoPrecedente < '999999999999999999' ) )
     SET @ScontoPrevisto = 'superiore all"80%';
SET @AnnoConsiderato = 'ANNO PRECEDENTE';
fatturatocorrente:

------------USE CURRENT YEAR IF PREVIOUS SALES VOLUME IS 0---------
IF @FattAnnoPrecedente NOT LIKE '0' goto fatturatoesistente;


IF (@FattAnnoCorrente > '0' and @FattAnnoCorrente < @40 ) and @Sconto < '40' goto finescript;
IF (@FattAnnoCorrente > @40 and @FattAnnoCorrente < @50 ) and (@Sconto > '40' and @Sconto < '50') goto finescript;
IF (@FattAnnoCorrente > @50 and @FattAnnoCorrente < @60 ) and (@Sconto > '50' and @Sconto < '60') goto finescript;
IF (@FattAnnoCorrente > @60 and @FattAnnoCorrente < @70 ) and (@Sconto > '60' and @Sconto < '70') goto finescript;
IF (@FattAnnoCorrente > @70 and @FattAnnoCorrente < @80 ) and (@Sconto > '70' and @Sconto < '80') goto finescript;
IF (@FattAnnoCorrente > @80 and @FattAnnoCorrente < '999999999999999999' ) and @Sconto > '80' goto finescript;


------------------------------------FIND SUGGESTED DISCOUNT ------
--SET @FattAnnoCorrente = '1';
IF ((@FattAnnoCorrente > '0' and @FattAnnoCorrente < @40 ))
     SET @ScontoPrevisto = 'inferiore al 40%';
IF ((@FattAnnoCorrente > @40 and @FattAnnoCorrente < @50 ))
     SET @ScontoPrevisto = 'compreso tra 40% e 50%';
IF ((@FattAnnoCorrente > @50 and @FattAnnoCorrente < @60 ))
     SET @ScontoPrevisto = 'compreso tra 50% e 60%';
IF ((@FattAnnoCorrente > @60 and @FattAnnoCorrente < @70 ))
     SET @ScontoPrevisto = 'compreso tra 60% e 70%';
IF ((@FattAnnoCorrente > @70 and @FattAnnoCorrente < @80 ))
     SET @ScontoPrevisto = 'compreso tra 70% e 80%';
IF ((@FattAnnoCorrente > @80 and @FattAnnoCorrente < '999999999999999999'))
      SET @ScontoPrevisto = 'superiore all"80%';
SET @AnnoConsiderato = 'ANNO CORRRENTE';
IF @Sconto LIKE '0.0%' SET @ScontoPrevisto = 'da stabilire in base alla merce ordinata'

fatturatoesistente:

-----------
--- HERE THERE WAS SOME TABLES CALLED BELOW BUT THEY WORK FINE, SO I REMOVED THEM ---
---------------------------------
---HTML EMAIL BODY SET WITH ALL VARIABLES, ALL WORKING FINE BUT THE @SCONTOPREVISTO is the wrong one----
SET @Email = 
    N'......HTML CODE....' + @ScontoPrevisto + '..HTML CODE...';

SET @oggettomail = 'ERRATA SCONTISTICA PER ' + @Cliente;
IF @Emailis null goto finescript;
EXEC msdb.dbo.sp_send_dbmail 
    @recipients = 'email@gmail.com',
    @subject = @oggettomail,
    @body = @Email,
    @body_format = 'HTML' ; 

finescript:
--take the next customerE---
FETCH NEXT FROM c INTO @CodiceCliente,@Cliente
END
--clean---
CLOSE c
DEALLOCATE c

The result of this query for @ScontoPrevisto, suggested discount is wrong, it is between 70% and 80 % but as you see the previous year sales volume is about 25000 so the right discount must be 50-60%. I dont' understand why. Instead for some customer, reslt is good. Another customer has

Sales Volume 2016--->0 Sales Volume 2015 ---> 0 Discount 60%

Result is greater then 80 % instead to be smaller than 40 %. I wait for your answer. Thank you guys!

Select from two tables without CommonElement

I want making select from two tables without any common element I'm trying this code, but i get incorrect syntax near ','.

select top 1 inventory.name,customer.name from inventory where inventor.name='test' ,  customer where customer.name='test2'

Get Max Entry_Sr_no from another table in SP

I have a SP, which gives me mkey and doc_no from one table.

Now I want to get the max of entry_sr_no of that respective mkey from the another table.

Here is my SP

alter procedure set_auto_action
    as 
        begin

            select mkey, doc_no from inward_doc_tracking_hdr 
           where status_flag not in (5,13)      
    end

I want to get max from inward_doc_tracking_trl table

The relation of both the table is something like below

inward_doc_tracking_hdr table mkey is equal to inward_doc_tracking_trl table ref_mkey

kindly suggest how to do this in SP

mardi 16 août 2016

How to check Current SQL Statement inside Stored Procedure in SQL Server

Please tell me how to check Currently executing SQL Statement called inside a Stored Procedure in SQL Server and its rows affected [ if DML, so far count like ROWS_PROCESSED in Oracle].

Select all results but Order by condition on single column

I've some records in a table like below:

ID  Name Group JoinDate    ActiveDate
1   A    12    11-01-2015  25-05-2015
2   A    19    12-06-2014  27-08-2015
3   B    16    03-09-2015  12-04-2016
4   B    35    05-05-2013  21-07-2015
5   B    39    06-09-2015  14-08-2016

From the data i need a result set like below: PS: Result set is based on the ActivityDate order by desc

Result:

ID  Name Group JoinDate    ActiveDate
2   A     19   12-06-2014  27-08-2015
1   A     12   11-01-2015  25-05-2015
5   B     39   06-09-2015  14-08-2016
3   B     16   03-09-2015  12-04-2016
4   B     35   05-05-2013  21-07-2015

Any Suggestions?

How to install sql2005 on sql2008r2?

I am poorly experienced in SQL Server installations. I have already installed 2008r2 on Microsoft Windows 8.

Now I want to install MS SQL Server 2005, but I need both MS SQL Server 2008r2 and MS SQL Server 2005.

How can I install this?

lundi 15 août 2016

total server memory - what is the most accurate way to get it through sql server?

How is it that the values of these 2 queries disagree between each other:

SELECT [server memory] = physical_memory_in_bytes /1024.00/1024.00/1024.00
FROM sys.dm_os_sys_info;



SELECT object_name, cntr_value 
  FROM sys.dm_os_performance_counters
  WHERE counter_name = 'Total Server Memory (KB)';

they should both be showing the total server memory.

why do they disagree?

enter image description here

enter image description here

Using SQL Profiler to get the name of stored procedures

I have a database with almost a thousand of stored procedures and I want to know which stored procedure is called after a button is clicked. I try to use SQL Profiler (version 8.0) to capture the name of the stored procedure, but it seems it's not possible to get the name directly from SQL Profiler.

A tutorial says I can get the stored procedure name by running:

Select name from sysobjects where id = <ObjectID>

I tried by the id matched nothing. How can I get the name of the stored procedure?

Thanks

vendredi 12 août 2016

Adding Row in existing table (SQL Server 2005)

I want to add another row in my existing table and I'm a bit hesitant if I'm doing the right thing because it might skew the database. I have my script below and would like to hear your thoughts about it.

I want to add another row for 'Jane' in the table, which will be 'SKATING" in the ACT column.

Table: [Emp_table].[ACT].[LIST_EMP]

enter image description here

My script is:

INSERT INTO [Emp_table].[ACT].[LIST_EMP]
([ENTITY],[TYPE],[EMP_COD],[DATE],[LINE_NO],[ACT],[NAME])
VALUES
('REG','EMP','45233','2016-06-20 00:00:00:00','2','SKATING','JANE')

Will this do the trick?

How to construct query to change the output of an sql table

I need some little help here...So, let me introduce you my problem. I have the following SQL table:

| RankCode | SeaPortInd | WatchKeepingInd |      EffectiveDate      | VesselCode |        FromDate         |         ToDate          |        LastDate         | LastUser |
+----------+------------+-----------------+-------------------------+------------+-------------------------+-------------------------+-------------------------+----------+
| C/E      |          0 |               0 | 1900-01-01 00:00:00.000 |        031 | 1900-01-01 05:00:00.000 | 1900-01-01 07:00:00.000 | 2016-08-11 12:40:00.000 | d.baltas |
| C/E      |          0 |               0 | 2016-06-02 00:00:00.000 |        031 | 1900-01-01 00:00:00.000 | 1900-01-01 00:00:00.000 | 1900-01-01 00:00:00.000 | d.baltas |
| C/E      |          0 |               1 | 2016-06-01 00:00:00.000 |        031 | 1900-01-01 01:00:00.000 | 1900-01-01 02:00:00.000 | 2016-08-11 17:58:00.000 | d.baltas |
| C/E      |          0 |               1 | 2016-06-02 00:00:00.000 |        031 | 1900-01-01 01:00:00.000 | 1900-01-01 02:00:00.000 | 2016-08-10 17:58:00.000 | d.baltas |
| C/E      |          1 |               1 | 2016-06-01 00:00:00.000 |        031 | 1900-01-01 03:00:00.000 | 1900-01-01 04:00:00.000 | 2016-08-10 17:58:00.000 | d.baltas |
| MSTR     |          0 |               0 | 2016-06-02 00:00:00.000 |        031 | 1900-01-01 16:00:00.000 | 1900-01-01 22:00:00.000 | 2016-08-10 17:58:00.000 | d.baltas |
| MSTR     |          0 |               1 | 2016-06-01 00:00:00.000 |        031 | 1900-01-01 08:00:00.000 | 1900-01-01 12:00:00.000 | 2016-08-10 17:58:00.000 | d.baltas |
| MSTR     |          1 |               0 | 2016-06-03 00:00:00.000 |        031 | 1900-01-01 08:00:00.000 | 1900-01-01 14:00:00.000 | 2016-08-11 15:00:00.000 | d.baltas |
+----------+------------+-----------------+-------------------------+------------+-------------------------+-------------------------+-------------------------+----------+

I want to take an output like this table:

enter image description here

Some more explanation of table:

Scheduled daily work hours at sea means SeaPortInd = 1

Scheduled daily work hours at port means SeaPortInd = 0

Watchkeeping means WatchkeepingInd = 1

NonWatchkeeping means WatchkeepingInd = 0

I managed to take to the following table:

+----------+--------------------+
| RankCode | SeaNonWatchkeeping |
| C/E      |  00:00 - 00:00     |
|          |  05:00 - 07:00     |
| MSTR     |  16:00 - 22:00     |
+----------+--------------------+

with the query:

SELECT CASE 
        WHEN row_number() OVER (
                PARTITION BY RankCode ORDER BY FromDate asc
    ) = 1
            THEN RankCode
        ELSE ''
        END AS RankCode

    ,substring(convert(VARCHAR(255), FromDate, 120), 11, 6) + ' -' + substring(convert(VARCHAR(255), ToDate, 120), 11, 6) AS SeaNonWatchkeeping

FROM WorkingHoursSchedule WHERE SeaPortInd = 0 AND watchkeepingind = 0

Can you please help me how to get the cases SeaportInd = 0 and Watchkeeping= 1 etc?

I use SQL SERVER 2008 but the query will also run at some previous versions sith minimum SQL SERVER 2005

Thanks in advance!!

jeudi 11 août 2016

case statement in where clause,should not check only for specific values

i need a CASE statement in where clause:

lets say we have two tables X and Y X have 3 columns namely EmpId,Name,JoinDate,DeptID Y have 4 columns namely EmpId,JoinDate,DeptID,DeptRefCd

I've to get the results so that except for X.deptId in (1,2,3) it should check for X.JoinDate=ISNULL(Y.JoinDate,'').i.e., it have to ignore the JoinDate condition deptId= 1 ,2 ,3

I've written as below,but its showing error: CASE WHEN X.deptId NOT IN ('4','5','6') THEN X.JoinDate=ISNULL(Y.JoinDate,'') END

Please suggest.

Query optimization. Duplicate subqueries

We found a slow query in our legacy system. What I see in the query is a duplicate fragment. Here's the full query:

DECLARE @SellerId INT;
DECLARE @DateFrom DATETIME;
DECLARE @DateTo DATETIME;

SET @SellerId = 5396884;
SET @DateFrom = '2016-01-05';
SET @DateTo = '2016-10-08';

DECLARE @CurrentDate DATETIME;
SET @CurrentDate = GETDATE();



CREATE TABLE #ReportDate (codes INT, dates DATETIME);
DECLARE @dif as INT;
DECLARE @cont as INT;
DECLARE @currdate as DATETIME;
SET @dif = DATEDIFF(day, @DateFrom, @DateTo);
SET @cont = 1;
SET @currdate = @DateFrom - 1;
WHILE (@cont <= @dif + 1)
BEGIN
    SET @currdate = DATEADD(DAY, 1, @currdate);
    INSERT INTO #ReportDate VALUES (@cont, @currdate);
    SET @cont = @cont + 1;
END


/* HOW TO OPTIMIZE THIS ONE? */
SELECT
        #ReportDate.dates as valid_date,
        (
          SELECT 

          COUNT(DISTINCT(nonCancelledSales.num_remito)) as actives

          FROM      
                (

                    SELECT *

                    FROM salesView

                    WHERE

                        salesView.sell_id NOT IN 
                            (
                              SELECT sell_id

                              FROM salesStates

                              WHERE
                                  salesStates.aborted = 1
                            ) 

                  ) nonCancelledSales

          WHERE
                nonCancelledSales.seller_id = @SellerId AND
                nonCancelledSales.cancelled = 0 AND
                nonCancelledSales.void = 0 AND
                nonCancelledSales.hasDiscount = 0 AND
                nonCancelledSales.dateOfSale <=  #ReportDate.dates AND
                nonCancelledSales.currentState =  (SELECT   MAX(hveest.date)

                                              FROM  salesStates hveest

                                              WHERE 
                                                    hveest.sell_id = nonCancelledSales.sell_id AND
                                                    hveest.date <= #ReportDate.dates) AND
                nonCancelledSales.lastProductDate = (SELECT     MAX(hvepro.date)

                                              FROM  productHistory hvepro

                                              WHERE 
                                                    hvepro.sell_id = nonCancelledSales.sell_id AND
                                                    hvepro.date <= #ReportDate.dates) 

        ) total_actives,

        (
          SELECT 

          ISNULL(SUM(nonCancelledSales.paymentValue),0) as active

          FROM      
                (

                    SELECT *

                    FROM salesView

                    WHERE

                        salesView.sell_id NOT IN 
                            (
                              SELECT sell_id

                              FROM salesStates

                              WHERE
                                  salesStates.aborted = 1
                            ) 

                  ) nonCancelledSales

          WHERE
                nonCancelledSales.seller_id = @SellerId AND
                nonCancelledSales.cancelled = 0 AND
                nonCancelledSales.void = 0 AND
                nonCancelledSales.hasDiscount = 0 AND
                nonCancelledSales.dateOfSale <=  #ReportDate.dates AND
                nonCancelledSales.currentState =  (SELECT   MAX(hveest.date)

                                              FROM  salesStates hveest

                                              WHERE 
                                                    hveest.sell_id = nonCancelledSales.sell_id AND
                                                    hveest.date <= #ReportDate.dates) AND
                nonCancelledSales.lastProductDate = (SELECT     MAX(hvepro.date)

                                              FROM  productHistory hvepro

                                              WHERE 
                                                    hvepro.sell_id = nonCancelledSales.sell_id AND
                                                    hvepro.date <= #ReportDate.dates)             
        ) active
FROM 
        #ReportDate
GROUP BY
        #ReportDate.dates



DROP TABLE #ReportDate

Here are the two duplicated fragments I see:

(
          SELECT 

          COUNT(DISTINCT(nonCancelledSales.num_remito)) as actives

          FROM      
                (

                    SELECT *

                    FROM salesView

                    WHERE

                        salesView.sell_id NOT IN 
                            (
                              SELECT sell_id

                              FROM salesStates

                              WHERE
                                  salesStates.aborted = 1
                            ) 

                  ) nonCancelledSales

          WHERE
                nonCancelledSales.seller_id = @SellerId AND
                nonCancelledSales.cancelled = 0 AND
                nonCancelledSales.void = 0 AND
                nonCancelledSales.hasDiscount = 0 AND
                nonCancelledSales.dateOfSale <=  #ReportDate.dates AND
                nonCancelledSales.currentState =  (SELECT   MAX(hveest.date)

                                              FROM  salesStates hveest

                                              WHERE 
                                                    hveest.sell_id = nonCancelledSales.sell_id AND
                                                    hveest.date <= #ReportDate.dates) AND
                nonCancelledSales.lastProductDate = (SELECT     MAX(hvepro.date)

                                              FROM  productHistory hvepro

                                              WHERE 
                                                    hvepro.sell_id = nonCancelledSales.sell_id AND
                                                    hvepro.date <= #ReportDate.dates) 

        ) total_actives,

        (
          SELECT 

          ISNULL(SUM(nonCancelledSales.paymentValue),0) as active

          FROM      
                (

                    SELECT *

                    FROM salesView

                    WHERE

                        salesView.sell_id NOT IN 
                            (
                              SELECT sell_id

                              FROM salesStates

                              WHERE
                                  salesStates.aborted = 1
                            ) 

                  ) nonCancelledSales

          WHERE
                nonCancelledSales.seller_id = @SellerId AND
                nonCancelledSales.cancelled = 0 AND
                nonCancelledSales.void = 0 AND
                nonCancelledSales.hasDiscount = 0 AND
                nonCancelledSales.dateOfSale <=  #ReportDate.dates AND
                nonCancelledSales.currentState =  (SELECT   MAX(hveest.date)

                                              FROM  salesStates hveest

                                              WHERE 
                                                    hveest.sell_id = nonCancelledSales.sell_id AND
                                                    hveest.date <= #ReportDate.dates) AND
                nonCancelledSales.lastProductDate = (SELECT     MAX(hvepro.date)

                                              FROM  productHistory hvepro

                                              WHERE 
                                                    hvepro.sell_id = nonCancelledSales.sell_id AND
                                                    hvepro.date <= #ReportDate.dates)             
        ) active

Is it fully necessary to duplicate the query ? In the first one he's getting:

 COUNT(DISTINCT(nonCancelledSales.num_remito)) as actives

on the second one:

  ISNULL(SUM(nonCancelledSales.paymentValue),0) as active

I suppose there has to be some way to rewrite the query but I'm not sure how.

Column returning null values instead of values present

I have a query in which, I have merged a sub query for my requirement.

Here the query is.

select a.mkey, b.mkey RefMkey, a.doc_no, a.doc_date, 
            e.type_desc DocType, c.first_name + ' ' + c.last_name CurrentUser,
        d.Type_desc Department, b.remarks, 
                (select f.type_desc from type_mst_a where f.Add_IInfo1
                 = b.NStatus_flag and f.type_code = 'S2') currentStatus
           from inward_doc_tracking_hdr a
        inner join inward_doc_tracking_trl b
            on a.mkey = b.ref_mkey
        inner join user_mst c
            on c.mkey = b.CUser_Id  
        inner join type_mst_a d
            on d.master_mkey = b.CDept_Id   
        inner join type_mst_a e
            on e.master_mkey = a.doc_type
        inner join type_mst_a f 
            on f.master_mkey = b.NStatus_flag
where a.mkey = 227394

but what happening here is, there are values present but I am getting as NULL

Update

CREATE TABLE [dbo].[Inward_Doc_Tracking_Hdr](
[Mkey] [numeric](18, 0) NOT NULL,
[FModule_ID] [char](1) NOT NULL,
[Comp_Mkey] [numeric](4, 0) NOT NULL,
[Branch_Mkey] [numeric](4, 0) NOT NULL,
[Tran_Type] [varchar](6) NOT NULL,
[Tran_Code] [numeric](8, 0) NOT NULL,
[Tran_No] [numeric](4, 0) NOT NULL,
[Department_ID] [varchar](4) NOT NULL,
[User_Id] [numeric](10, 0) NULL,
[Doc_Type] [numeric](10, 0) NULL,
[Doc_No] [varchar](30) NULL,
[Doc_Date] [datetime] NOT NULL,
[Dispatch_By] [char](1) NOT NULL,
[Status_Flag] [numeric](8, 0) NOT NULL,
[FA_Year] [smallint] NOT NULL,
[Party_Mkey] [numeric](10, 0) NULL,
[To_Department] [numeric](10, 0) NULL,
[To_User] [numeric](10, 0) NULL,
[Inward_Amt] [numeric](18, 3) NULL,
[Ref_No] [varchar](40) NULL,
[Ref_date] [datetime] NULL,
[U_DateTime] [datetime] NOT NULL,
[LastAction_DateTime] [datetime] NULL,
[Remarks] [varchar](255) NULL,
[Delete_Flag] [char](1) NOT NULL,
[Outward_Type] [char](1) NULL,
[Doc_Department] [numeric](10, 0) NULL,
[Party_Name] [varchar](80) NULL,
[Delivered_By] [varchar](30) NULL,
[Doc_Description] [varchar](50) NULL,
[Last_Department] [numeric](10, 0) NULL,
[Last_User] [numeric](10, 0) NULL,
[Approved_Amount] [float] NULL,
[Chq_No] [varchar](50) NULL,
[Chq_dated] [datetime] NULL,
[Chq_Bank] [varchar](40) NULL,
[Chq_Amount] [float] NULL,
[Vendor_MKey] [int] NULL,
[Vendor_Comp_Mkey] [int] NULL,
[Project_Mkey] [numeric](10, 0) NULL,
[Program_mkey] [numeric](10, 0) NULL,
[Payment_MKey] [int] NULL,
[Due_Date] [datetime] NULL,
[Updated_Remarks] [varchar](500) NULL,
[Updated_Bill_no] [varchar](27) NULL,
[Updated_Bill_Date] [datetime] NULL,
[Updated_Bill_Amt] [float] NULL,
[TotalDeductions] [float] NULL,
[Broker_Mkey] [numeric](10, 0) NULL,
[Customer_Mkey] [numeric](10, 0) NULL,
[Payable_Amt] [float] NULL,
[Balance_Amt] [float] NULL,
[Req_Bill_Flag] [char](1) NULL,
[Po_No] [varchar](50) NULL,
[Receipt_No] [varchar](50) NULL,
[Bill_No] [varchar](50) NULL,
[Org_id] [varchar](10) NULL,
[Site_Id] [varchar](50) NULL,
[Site_Name] [varchar](150) NULL,
[Cumulative_Amt] [numeric](18, 2) NULL,
[Email_Id] [varchar](50) NULL,
[Emp_Id] [varchar](6) NULL,
[Disp_through] [varchar](50) NULL,
[Disp_Through_Name] [varchar](100) NULL,
[Last_To_User] [numeric](10, 0) NULL

) ON [PRIMARY]

The query which shows there are result is

select type_desc, * from type_mst_a where type_code = 'S2'

Edit Puch in and Punch out time in sql 2005

is that any way to edit punch in or punch out time in soft using sql backend.

NT Service\MSSQLSERVER as Administrator - Impact

To be able to execute some of the application like Databasemail.exe from SSMS, the ID running the SQL Service needs to be part of the Windows Administrator group.

My SQL Server service is running with ID "NT Service\MSSQLSERVER".

What will be the impact if I add this ID or other system account to admin group?

mercredi 10 août 2016

Upgrade from Sql Server Entreprise to Evaluation edition, it is possible?

I'm having some trouble upgrading from an Entreprise edition of Sql Server 2008 R2 SP2 to an Evaluation of Sql Server 2014 SP1, and I begin to wonder if it is possible? I didn't found anything about it in the supported version and edition upgrade guide : http://ift.tt/2aAzUlg

It says that you can't migrate from SQL Server 2014 Entreprise to Evaluation, but it says nothing about previous editions.

Thanks.

mardi 9 août 2016

Where Strange Results

I'm using this query to obtain payments from customer still not payed. So I need to exclude all kind in the where clause. I tryed with <> and != and Not Like but It show me all payment, also with those I've excluded in the where clause. Do you see something that I don't see?

SELECT td= CODCLIFOR,      '', 
            td= DSCCONTO1,      '',  
            td= ANAGRAFICACF.TELEX,      '', 
            td= NUMDOC,      '', 
            td= NUMSCAD,      '', 
            td= CONVERT (VARCHAR(30),DATASCADENZA,105),      '', 
            td= '€ ' + REPLACE(CONVERT(varchar, CAST(IMPORTOSCLIT AS money), 105),',','.') ,       '', 
            td= TIPIEFFETTI.DESCRIZIONE,ESITO
            FROM dbo.TABSCADENZE
            INNER JOIN dbo.ANAGRAFICACF ON CODCLIFOR = CODCONTO
            INNER JOIN dbo.TIPIEFFETTI ON TIPOEFFETTO = EFFETTO
            INNER JOIN dbo.BANCAAPPCF ON CODCLIFOR = BANCAAPPCF.CODCONTO AND BANCAAPPCF.CODICE = TABSCADENZE.BANCAAPPOGGIO
            INNER JOIN  dbo.ANAGRAFICABANCHE ON BANCAINC = CODBANCA
            WHERE  (TABSCADENZE.TIPOEFFETTO NOT LIKE '%2%' OR TABSCADENZE.TIPOEFFETTO NOT LIKE '%10%') AND (TABSCADENZE.ESITO NOT LIKE '%1%' OR  TABSCADENZE.ESITO NOT LIKE '%2%' OR  TABSCADENZE.ESITO NOT LIKE '%4%')  AND  CODCLIFOR LIKE '%C%'
            ORDER BY CODCLIFOR DESC

Thank You!

Description of NStatus_flag not coming proper from query

I have created a query in which I want the description for NStatus_flag which comes from

select * from type_mst_a where type_code = 'S2'

have a look

img

but when I run in the beloq query, I dont proper result.

select a.mkey, b.mkey, b.CUser_Id, c.first_name + ' ' + c.last_name CurrentUser,
    d.Type_desc Department, e.Type_desc
     from inward_doc_tracking_hdr a
        inner join inward_doc_tracking_trl b
            on a.mkey = b.ref_mkey
        inner join user_mst c
            on c.mkey = b.CUser_Id  
        inner join type_mst_a d
            on d.master_mkey = b.CDept_Id   
        inner join type_mst_a e
            on e.master_mkey = b.NStatus_flag -- and e.Type_code = 'S2' 
    where a.mkey = 227423

Let me know where I am wrong

SSRS 2005 with ASP.NET Report Viewer

Hi unfortunately we only have SQL Server 2005 so I am stuck with SSRS 2005. I have created a report and runs as expected. I have an issue though. When I combine it with the Microsoft Report Viewer it's width is shrunk. I have noticed this comes back to normal if I force my app to use IE7 however then i'm on a whole totally different issue with the site not looking quite right and some of the Ajax functionality does not work slickly as I would like it. is there anything I can do, looking at the HTML it looks as if the SSRS report is adding a table and a column after my report. Can anyone help remove this, as it does not look professional.

Thanks

lundi 8 août 2016

operand type clash:image is incompatible with xml

When i try to insert the dynamically created xml into a temp table its shows a error

"operand type clash :image is incompatible with xml".

I already split the query when I execute the query and just select the xml its working .Only problem is that its not allow to insert into a table.

   "SET @sSQL1 = '
     SELECT  ' + @ColumnList + '
     FROM TB1 IPI WHERE  TBID= ' + CAST(@ID as varchar(10)) +' FOR XML RAW (''TB'') ,ROOT(''Table'') '

INSERT INTO @TBLTRANSXML(INCTRANSXML)           
EXEC (@sSQL1)"

The code is attached as picture

enter image description here

Please help its urgent.

Drop table with foreign key

I'm trying this code

Drop Table Inventory

I get error:

Could not drop object 'Inventory' because it is referenced by a FOREIGN KEY constraint.

vendredi 5 août 2016

Treating multiple delimiter separated fields as distinct rows

I inherited a table (who hasn't, right?) that has data that looks like this:

Item          |             Properties        |        Quantity
--------------------------------------------------------------------
Shirt         |  button-down,polo,sleeveless  |          4,5,8

For the short term, I want to create a view, but eventually I want to export the data to a new version of the table when time allows and have it more like:

Item          |             Properties        |        Quantity
--------------------------------------------------------------------
Shirt         |            button-down        |            4   
Shirt         |               polo            |            5
Shirt         |             sleeveless        |            8

Essentially, take multiple column groups (I imagine there will be other tables where there are more columns than two with this sort of behavior) that are known to be delimiter separated and break them into distinct rows? Any other rows gathered that aren't like this would be shared amongst them like Item in this example. # of commas are uniform between these types.

edit: I used the function given in the answer to How to convert comma separated NVARCHAR to table records in SQL Server 2005? and this is currently what I have:

select distinct data.item, tmptbl.[String] from
  data cross apply [ufn_CSVToTable](data.properties, ',') tmptbl ...

This works in the single column context, but applying that function to a second column (quantity in this case) outright would generate every possible combination of properties and quantities, right? In fact, yes it did result in that when I attempted. It would seem I'd need a cursor or similar to effectively break into individual rows of properties[i] | quantity[i], will try and construct that. That or may just select the data over and split it on the application side.

SQL2005 - DATE ADD AND GETDATE DOESN'T WORK

I have a very strange error in a SQL query and I don't understand why.

SELECT 
            CODCLIFOR,      '', 
            DSCCONTO1,      '',  
            NUMDOC,      '', 
            NUMSCAD,      '', 
            DATASCADENZA,      '', 
            REPLACE(CONVERT(varchar, CAST(IMPORTOSCLIT AS money), 105),',','.') ,       '', 
            BANCAAPPCF.BANCAAPPOGGIO,    '',
            TIPIEFFETTI.DESCRIZIONE
            FROM dbo.TABSCADENZE
            INNER JOIN dbo.ANAGRAFICACF ON CODCLIFOR = CODCONTO
            INNER JOIN dbo.TIPIEFFETTI ON TIPOEFFETTO = EFFETTO
            LEFT JOIN dbo.BANCAAPPCF ON CODCLIFOR = BANCAAPPCF.CODCONTO AND BANCAAPPCF.CODICE = TABSCADENZE.BANCAAPPOGGIO
            WHERE    TIPOEFFETTO = 2  AND DATASCADENZA ='2016-08-05' AND CODCLIFOR LIKE '%C%'
            ORDER BY BANCAAPPCF.BANCAAPPOGGIO DESC

On date DATASCADENZA in the where condition, if I put the today date like '2016-08-05' I've results.. instead if I use GETDATE() or DATEADD(DAY,3,GETDATE()) I obtain 0 results... I don't understand why. Can you help me? Thank you!

mardi 2 août 2016

SQL2005: LOOP THE SAME QUERY FOR EVERY ROW OF ANOTHER TABLE

I'm tryng to obtain a loop result for each row in a different table. I need to know which product line, each sales agent, sell in a month. I've the query that show me how to know the total of product lines. I need only to insert inside it, the "CODAGENT" in the where condition, looping trough each agent in the Agents TABLE. So to make an example not in sql language.

-----THIS IS NOT A USEFUL CODE, IT'S ONLY FOR UNDERSTANDING----
For Each Row in Agents TAble Do
Set #CODAGENT = Row 1,2,3,....
Select
-routine for selecting what i need with inside WHERE CODAGENT =  #CODAGENT 
Next Row
-----THIS IS NOT A USEFUL CODE, IT'S ONLY FOR UNDERSTANDING----

Thank you guys

lundi 1 août 2016

Sql 2005 Find customers that doesn't order from one year

I'm trying to found in DB SQL 2005 customers names that doesn't order or ask for quotation from one year. I'm trying this but it doesn't work, because it show me only documents older than one year, but show them also if in the current year other documents of the same customers are presents.

    SELECT DISTINCT ANAGRAFICACF.CODCONTO,
                    DSCCONTO1,
                    '€ '+LEFT(TOTDOCUMENTO,LEN(TOTDOCUMENTO)-2),
                   CONVERT(VARCHAR(11),DATADOC,6),
                     TESTEDOCUMENTI.TIPODOC,
                     ANAGRAFICACF.PARTITAIVA,
                     ANAGRAFICACF.CODFISCALE,
                     ANAGRAFICARISERVATICF.NOTE1,
                    TESTEDOCUMENTI.DATADOC,
                     TESTEDOCUMENTI.CODAGENTE1,
                     ANAGRAFICAAGENTI.DSCAGENTE 
FROM dbo.TESTEDOCUMENTI 
INNER JOIN dbo.ANAGRAFICACF
ON CODCLIFOR=CODCONTO
INNER JOIN dbo.RIGHEDOCUMENTI
ON PROGRESSIVO=IDTESTA AND TOTNETTORIGA <>'0'
INNER JOIN dbo.ANAGRAFICARISERVATICF
ON CODCLIFOR=ANAGRAFICARISERVATICF.CODCONTO
LEFT JOIN dbo.ANAGRAFICAAGENTI
ON CODAGENTE=TESTEDOCUMENTI.CODAGENTE1
WHERE  (dbo.TESTEDOCUMENTI.TIPODOC = 'ORDER' or dbo.TESTEDOCUMENTI.TIPODOC = 'QUOTATION') AND (dbo.TESTEDOCUMENTI.DATADOC < DATEADD(DAY, -365, GETDATE() ) AND NOT dbo.TESTEDOCUMENTI.DATADOC BETWEEN DATEADD(DAY, -365, GETDATE() ) AND GETDATE())
ORDER BY TESTEDOCUMENTI.DATADOC DESC

Thank you guys!