dimanche 31 janvier 2016

How can I delete these rows and columns that were created from excel?

I have this doubt. I have charged a sheet of excel from SQL Server 2008 and this shows all the data what contains the sheet. I wish to have the data that I want and I can save these records in a some table. But I need to know How can I delete all the data that I dont need rows and columns of the sheet. Please I need you can help me.

I have it that I allow me import my sheet of Excel

select *  into #TBL_DATA  from openrowset('Microsoft.ACE.OLEDB.12.0',    'Excel 12.0; Database=C:\Microsoft\siac.xls; HDR=YES; IMEX=1', 
'select * from [Campo23$]')

This the image as shows in the query.

enter image description here

Thanks in advance.

samedi 30 janvier 2016

SQL Stored procedure returning resulr ROw Multiple time it shows 1 rows to 3 times

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[PrintQuickBill](@BillNo int)
as
SELECT  
A.BillNo, 
A.BillDate, 
A.CustomerName, 
A.Address, 
A.CustomerId, 
A.BillLaborAmt, 
A.BillPartAmt, 
A.ServTaxAmt, 
A.VatAmt,
A.BillNetAmt,

FROM         
dbo.tblQuickBillMain A

INNER JOIN
[dbo].tblQuickBillLabor L ON A.BillNo = L.BillNo
 INNER JOIN
 [dbo].tblQuickBillParts P ON  A.BillNo = P.BillNo
CROSS JOIN
dbo.CompanyInfo
where A.BillNo=@BillNo
order by CustomerName.

// this stored procedure returning result in multiple form like if I have 1 // record the result shows 3 times. // If I take BillNo=1 then it should retun only one row but it retun 3 row //which are identical means billNo 1 is shows three times with respective data.

vendredi 29 janvier 2016

How to create report table in sql?

I am creating In-patient management system desktop application in javafx as my mini project of MCA, which have some data about patient admitted in hospital. I have to save all the records of patient test & test reports in database. So, then i have created Test table with attributes ->(T_ID, P_ID, T_NAME, T_DATE) & Report table with attributes ->(R_ID, P_ID, P_NAME, T_DATE, REF_BY) So, there are multiple types of Test Report eg. CBC_REPORT, LFT_REPORT etc. then how should I create the relationship between this table. I tried but I am facing problem in USER INTERFACE for inputing values in table. Please help me becoz my project deadline is getting closer. Thanx in advance.

How I can read a sheet of Excel from sql server 2008?

Please need to help for this problem that I have. I need to read a sheet of excel from sql. I want to read this data what contains data and store in a temporal table. But right now I am having problems with read Excel because it shows me a error from sql. What I need for reading it

Error:
Not registered the OLE DB provider "Microsoft.ACE.OLEDB.12.0"

I hope you can help me with it problem, please.

I have executed it. Maybe I am missing something.

SELECT * --INTO TB_EXAMPLE FROM OPENROWSET('Microsoft.ACE.OLEDB.12.0', 'Excel 12.0; Database=C:\Microsoft\Test.xls; HDR=YES; IMEX=1', 'SELECT * FROM [Plan1$]') GO

Thanks in advance.

T-SQL Distinct Close Dates

Using SQL Server 2005 I am selecting DATETIME from a set of two tables using a UNION. Many of these are very close together: e.g:

2016-01-29 10:28:57.540
2016-01-29 10:28:57.647
2016-01-29 11:23:18.193
2016-01-29 11:23:18.240

In this example I would like to get back just

2016-01-29 10:28:57.000  
2016-01-29 11:23:18.000

This is easy using some date/conversion functions to remove the ms part. However if we get the following:

2016-01-29 10:18:58.105
2016-01-29 10:18:57.952
2016-01-29 11:13:18.193
2016-01-29 11:13:18.240

I will get 3 datetimes when I only want 2:

2016-01-29 10:18:58.000
2016-01-29 10:18:57.000
2016-01-29 11:13:18.000

Instead of:

2016-01-29 10:18:58.000
2016-01-29 11:13:18.000

As 2016-01-29 10:18:58.105 and 2016-01-29 10:18:57.952 are less than a second apart.

So the question is how can I group together DATETIME values which are within a second of each other?

mercredi 27 janvier 2016

How to iterate through table for an sql job?

PerformanceReview

  • prID
  • reviewDate
  • passed
  • notes
  • successStrategy
  • empID
  • nextReviewDate

above is my table I am working with, my goal is to get the nextReviewDate check to see if it is within 7 days of the current date ( I will do this using DATEDIFF() ) and send an email to a specified email address if this condition is true.

My question is, how do I make it so that my sql job will perform this task for each performance review row in the table. I have researched and found information on CURSORS, or using WHILE loops being slow and inefficient for this task. Any help is appreciated as I am in the final stage of development :)

Sum MSSQL Count field from Grouped queryH

I am trying to write a query that takes all content from my db that has been rated higher than 3 stars and returns the top four modules based on star average and highest numbers of ratings. This part works great. But in order for me to put this into a graph, I need the percentage. So, I need the summary of the count(id_module) field. I have read through a lot of posts and tried to implement a number of solutions but have not been successful - can anyone shed any light for me? I have pasted my query below and the results it brings back - this part works fine... I just need to know how to get the sum of the id module fields - which in this case would be 23... thanks for any help offered!

SELECT TOP 4 AVG(rating) AS ratingstars, COUNT(id_module) AS countmodules,  FROM [db]
WHERE 
(rating > 3)
 GROUP BY id_module ORDER BY ratingstars DESC, countmodules DESC

ratingstars = 5, 5, 5, 5 countstar = 18, 2, 2, 1 (need the sum of these)

3rd highest salary using TOP

SELECT TOP 1 salary FROM (    
   SELECT TOP 3 salary     
   FROM employees     
   ORDER BY salary DESC) AS emp  
ORDER BY salary ASC

why is AS emp used in the query?? query does not work without using AS

mardi 26 janvier 2016

lundi 25 janvier 2016

MS SQL numeric data type and convertion with removing zero

create table test_int
    (
     num bigint
    )

insert into test_int (num)
values (4096);

My task is to calculate 4096/1024/1024 and get decimal answer. Ok, int doesn't store values after dot, so:

select CAST (num as decimal)/1024/1024 AS decimal, ROUND ((CAST (num as decimal)/1024/1024),4,1) AS numeric  from test_int

First one is pure resault, second one is after rounding:

decimal         numeric
0.00390625000 0.00390000000

The task is to remove empty zeroes after values.

select convert(decimal(25,5), 4096/1024/1024 ,0) 

returns 0.00000.

So how can I get 0.0039 instead of 0.00390000000? Thanks in advance for any kind of help.

using Case in select statement

I have a situation where I am summing up several columns from a table and inserting the results into another table. This is being grouped by county and district. One of the columns is also taking the smallest total sales from a retailer in that district. The problem I have is that there may be some that have less than zero total sales. I only want to write the smallest value that is greater than zero to that column.

declare @WeekEnd datetime
set @WeekEnd = (select top(1) date from sales order by date desc)
select date
,county
,district
,sum(prod1) 
,sum(prod2) 
,sum(prod3) 
,sum(prod4) 
,sum(prod1+prod2+prod3+prod4) --Total Sales
,Case when min(prod1+prod2+prod3+prod4) > 0 then min(prod1+prod2+prod3+prod4)
--this works well except for when a total is less than zero, then it is null. I want to avoid the null and have it write the smallest value greater than zero. 
end
from sales 
where date = @WeekEnd
group by date,county,district
order by county, district

SQL Server Service Broker - CHECKDB found consistency errors, how could this happen?

I encountered a weird SSB consistency problem, namely I have a queue that holds messages (status=1, Ready to receive) which are lying there for a very long time. In the meantime there was an upgrade from SQL 2005 to SQL 2012 and now when I want to do something with these messages (e.g. END CONVERSATION, even with CLEANUP) I get an error: The conversation handle "......." is not found. So I tried to look for this handle in sys.conversation_endpoints, but to my surprise it's not there. This shouldn't have happened, as far as I know if there are messages in the queue with associated conversation_group_id and conversation_handle, there should be an endpoint for each one.

I ended up running DBCC CHECKDB and got messages such as:

Msg 8997, Level 16, State 1, Line 1 Service Broker Msg 9708, State 1: The messages in the queue with ID some_number are referencing the invalid conversation group 'some_guid'.

Msg 8997, Level 16, State 1, Line 1 Service Broker Msg 9705, State 1: The messages in the queue with ID some_number are referencing the invalid conversation handle 'some_guid'.


So my question is: how could this happen? Are there any potential DEV/DBA errors or gotchas e.g. while performing SQL upgrade, that might lead to such corruption ?

jeudi 21 janvier 2016

SCope_Identity multiple insert

How can I avoid these type can I capture value for each identity insert and insert in other table

Insert into LookupTables (a, b, c, d, e, OtherInfo, SortOrder)
Values (a, b, c, d, e, NULL, NULL)

DECLARE @LookupID INT = SCOPE_IDENTITY() 

Insert into LookupTables (a, b, c, d, e, OtherInfo, SortOrder)
Values (a, b, c, d, e, @LookupID, NULL)

Insert into LookupTables (a, b, c, d, e, OtherInfo, SortOrder)
Values (a, b, c, d, e, NULL, NULL)

DECLARE @LookupID2 INT = SCOPE_IDENTITY() 

Insert into LookupTables (a, b, c, d, e, OtherInfo, SortOrder)
Values (a, b, c, d, e, @LookupID2, NULL)

query execution error in php

im creating a report using php and back end sql server 2005. i write the blew query this run fine in sql server while giving error when executing in php.

$query = "select distinct t1.VisitDate,t1.ReceiptNo,t1.VisitorNo,p.PatientName,STUFF((SELECT f.Particular + ', ' from CollectionPointTable t2,FeesTable f where t1.ReceiptNo = t2.ReceiptNo and f.ID=t2.TestID FOR XML PATH(''), TYPE ).value('.', 'VARCHAR(MAX)') ,1,0,'') Tests , sum(t1.payment) as Amount from CollectionPointTable t1,patientinformationtable p where p.visitorno=t1.visitorno and convert(varchar(10),t1.VisitDate,103)='$date' group by t1.Receiptno,p.patientname,t1.VisitorNo,t1.VisitDate order by ReceiptNo";

$stid =sqlsrv_query($conn, $query); $Today_patient_list = sqlsrv_fetch_array($stid,SQLSRV_FETCH_ASSOC);

that is the error which gives by Error Warning: sqlsrv_fetch_array() expects parameter 1 to be resource, boolean given in C:\wampnew\www\logs\viewTodaysCollection.php on line 65

mercredi 20 janvier 2016

cmd.ExecuteScalar return 1 when there is not data

I have this sql query to count data in a table

SELECT COUNT(*) as cn FROM mytable WHERE Item_id=3 AND service_id=20 
AND Min_Qty=1 AND Max_Qty=1  

and i used this to check

dim iCount as integer = 0
Using cmd As New SqlCommand(qb.GetQuery, conn, sqlTrans)
      iCount = Convert.ToInt32(cmd.ExecuteScalar().ToString())
End Using

but count has 1 when there is no data at all in the table

i had to use this to check

 Using cmd As New SqlCommand(qb.GetQuery, conn, sqlTrans)
    Using dr As SqlDataReader = cmd.ExecuteReader()
       iCount = If(dr.Read, 0, 1)
    End Using
  End Using

before i got count to be zero

what could be the problem?

Calculating sum with uneven rows from multiple table

enter image description here

I tried This with adding 2 data tables in vb.net but it fails when group has 3rd level child (for e.g. if added 12, regular fees,5 in group table) please tell me how i can i query database when child node creation is unlimited at group table

Most effective way to check sub-string exists in Comma separated string in SQL Server

I have a comma separated list field available which has values like 'Product1,Product2,Product3'. I need to search whether the given product name exists in this field.

I used below SQL and is working fine.

Select * from ProductsList where productname like '%Product1%'.

The above query is working very slow. Will there be a most effective way I can search for a Product Name in the comma separated list to improve the performance of the query. Please note I have to search comma separated list before performing any other select statements.

How to allow a dynamic amount of users certain database permissions?

I have spent the past month or so developing an application using Visual Studio 2015 Community Edition and SQL Server 2005 which is a Windows Forms application that accesses a database allowing the user to perform CRUD tasks.

My *question/problem* now is how do I allow for a user on a different machine but same local network, to sign into the application (generic username/password) and start interacting with the database/application without any user permission errors.

I understand how to create users and grant certain permissions to said users but I am wondering of a way to do this without having to create new credentials/permissions for each unique person that uses this application.

Kill Rollback SQL

I've tried to kill a rollback SPID and get a message as seen below. Please assist

transaction rollback in progress. Estimated rollback completion: 0%. Estimated time remaining: 0 seconds.

Change value of SSRS report parameter based on the input of another parameter

I have a SSRS 2005 report with three parameters: @FromDate, @ToDate and @Period. @FromDate and @ToDate default to the first day and the last day of last month, respectively.

The @Period parameter is a multi-value parameter. So if I choose for instance "Current quarter", I want the @FromDate and @ToDate to change to the corresponding values based on the input in @Period.

My problem is not getting the correct datetime expressions, but rather how to make the parameters interact with each other as desired.

mardi 19 janvier 2016

How to properly escape strings inside an T-QSL query which itself a string

I'm trying to create an SQL variable which will hold an SQL string that i will execute by calling EXEC(myVariable)

I have the below SQL script to create a stored procedure but when i execute it in management studio, it throws the following error

The replace function requires 3 argument(s).

Below is the full script

IF NOT EXISTS ( SELECT  * FROM    sys.objects WHERE   object_id = OBJECT_ID(N'SP_Test') AND type IN (N'P', N'SP_Test')) 
BEGIN
DECLARE @CreateSP varchar(MAX) = '
CREATE  PROCEDURE [dbo].[SP_Test]       
 (@Destination varchar(100),      
 @Period varchar(8000),      
 @ItemType varchar(100),      
 @Nationality  varchar(100))   

AS      
BEGIN      
 SET NOCOUNT ON;      

 Declare @sql as nvarchar(4000)   

 set @sql = ''SELECT distinct  Country.Country_ID,Country.Name, Destination.Destination_ID, Destination.Destination_Name,
   MyTableName.Year, Region.Region_ID,  rtrim(Region.Region_Name) as Category,    
 Count(MyTableName.Allegation) as AllegCnt INTO ##MyTableName_Temp
 FROM MyTableName INNER JOIN Destination on MyTableName.Destination_ID = Destination.Destination_ID
 INNER JOIN Country on  MyTableName.Country_ID=Country.Country_ID
  INNER JOIN Region on MyTableName.Region_ID=Region.Region_ID 
  where 1=1 and Country.Lang_ID=1200 
  AND MyTableName.Country_ID NOT LIKE ''%N/A%'' AND MyTableName.Region_ID != 1''   

 if @Destination is not  null      
 set @sql = @sql + '' AND MyTableName.Destination_ID IN ('' +@Destination+'')''      


 if @Period is not null      
 set @sql = @sql + '' AND Year IN ('' +@Period+'')''      


 if @ItemType is not null      
 set @sql = @sql + '' AND MyTableName.Region_ID IN ('' +@ItemType+'')''      


 if @Nationality  is not null      
 set @sql = @sql + '' AND MyTableName.Country_ID IN ('''''' +replace(@Nationality,'','','''','''')+''''+'')''   


 set @sql = @sql + '' GROUP BY MyTableName.Year,Destination.Destination_Name, Destination.Destination_ID,Country.Country_ID,Country.Name,Region.Region_ID,  Region.Region_Name       
 ORDER BY Name desc''      

 execute(@sql)      

 EXECUTE sp_Arrange      
 ''SELECT Name as Origin, Category, Total FROM ##MyTableName_Temp'',      
 NULL,      
NULL,      
''Origin'',
 ''Total'',    
 ''SUM''         
  drop table ##MyTableName_Temp      
END'      
 EXEC(@CreateSP) 
END

It looks like i'm not escaping the strings in the script properly.

apply to target server failed for job sql 2005

I'm trying to create a job by simple sql squery code, that is to delete a table and insert new filtered data from another table.

My script is

delete from table1

insert into table1

select * from table2

*Both tables have the same number of columns. That query was put into the Job step list.

enter image description here

samedi 16 janvier 2016

Mysql query with respect to triggers

I tried to get the following output through triggers in sql server 2005. I'm using the below query to change the values of age(column name) to zero, if it is less than zero.

Create trigger agecheck on account for insert as begin
Declare @age int
select @age=age from inserted if @age<0 set @age=0; end

I was able to execute this query successfully, but I'm not getting desired result. I'm using sql server 2005.

Could you please suggest on this.

How do i multiply a large number in sql with out getting a "overflow error " error

I know ths maybe a silly question but how do i multiply large numbers in sql server without getting an " Arithmetic overflow error converting expression to data type int " error ? I need to take a column that contains a list of 6 digit client numbers

Eg 123456, 123457 and make it 1234560000000 , 1234570000000 etc.

This is what i tried doing.

update account set sClientIdNo =  sClientIdNo * 100000000

But i end up with the overflow error. Any help will be greatly appriciated.

Thanks

jeudi 14 janvier 2016

SQLserver 2005 to 2012 com.microsoft.sqlserver.jdbc.SQLServerException: Implicit conversion from data type varbinary to datetime2 is not allowed

We are migrating from 2005 to 2012. One of the functionality is failing with this error com.microsoft.sqlserver.jdbc.SQLServerException: Implicit conversion from data type varbinary to datetime2 is not allowed. Use the CONVERT function to run this query.

We use SQLJDBC driver 3.0 to communicate with SQL server 2012. I see this issue is happening when we try to insert null value to datetime column (nullable column). Same however works in 2005. Any help with this issue is appreciated.

ASP development after SQL-Server goes down?

Scenario: ISS 8.5 is on our work machines, our Microsoft SQL server is currently down for an indeterminate amount of time, and we don't have a back-up. We can continue to develop code on localhost. Because the SQL server is down, we can't execute any data transactions. Are there any reliable resources online to, at least, test if the developed SQL syntax is correct?

mercredi 13 janvier 2016

SQL-Server 2005: multi-part identifier could not be bound

I'm working with SQL Server 2005, I'm new to SQL so bear with me.

The following aliased SQL query is giving me the following error:

The multi-part identifier "EquipmentDescription.DESCRIPTION" could not be bound.

SQL:

WITH somerows as 
(
    SELECT 
        Mastertable.ID, Mastertable.foo1, Mastertable.foo2, 
        Mastertable.foo3, EquipmentDescription.DESCRIPTION,
        ROW_NUMBER() OVER (ORDER BY Mastertable.ID) AS SeqValue 
    FROM 
        EquipmentDescription 
    LEFT JOIN 
        MasterTable ON EquipmentDescription.foo1 = MasterTable.foo1 
    ORDER BY 
        EquipmentDescription.DESCRIPTION
) 
SELECT * 
FROM somerows  
WHERE SeqValue BETWEEN 0 and 20

Background: Mastertable has 60,000+ records. I'm using WITH...as...etc to request 20 records at a time on the server side.

The DESCRIPTION column of EquipmentDescription for the purposes of design is not included in Mastertable. It is a requirement to include DESCRIPTION in the final select.

Any ideas on what I'm doing wrong?

how to Select getdate () in yyyy/M format

I want to select getdate() in the format yyyy/M. i tried to write a query as SELECT FORMAT(GETDATE(),'yyyy/M') but it is giving me error.I am a beginner in sql. how do i achieve yyyy/m format if there is only single digit month. eg. the query should give 2016/1 when there is only one digit month(it should not give 2016/01) and should give 2016/10 when the month is of two digits

SQL How to select first match if key has multiple values

Folks,

I have the following table...

Code UPC
1111 A
1111 B
1111 C
2222 B
2222 A

I need to return a table where only one UPC is returned per code (any code), so for table below result should only be 2 rows such as...

Code UPC
1111 A
2222 B

Appreciate any pointers.

How to Trim leading and trailing tab spaces in MSSQL query

I have data which has leading and trailing spaces in the string. when storing that data in database I want to trim the space in query itself before storing into DB.

Normal spaces are trimming properly with RTRIM and LTRIM function but if a string contains tab space,its not trimming the tab space from the input string.

Can anyone help me to get the string with trimmed with tab space from leading and trailing.

If select exists, use it. If not, try it on different table

I have a piece of code like this:

IF  EXISTS(SELECT VALUE
                FROM   tableA
                WHERE  nameid = 'thisName')
BEGIN   
    SELECT distinct VALUE
    FROM   tableA
    WHERE  nameid = 'thisName'
    ORDER BY value
END

ELSE BEGIN     
    SELECT distinct VALUE
    FROM   tableB
    WHERE  nameid = 'thisName'
    ORDER BY value
END

Basically select something from tableA, if I don't find result there, try it in tableB.

Is there a more efficient way how to write this? So I don't have to write select from tableA twice (once inside the EXISTS statement and once as the actual select).

I was toying with COALESCE, but it allows only one result, not a set.

mardi 12 janvier 2016

SQL server 2005 installation throwing error " sql service couldnt start"

i am trying to install SQL SERVER 2005 STANDARD EDITION on windows server 2003 R2, but everytime it throws error as "The SQL Server service failed to start for more information, see the SQL Server Books online topics, “How to : View SQL Server 2005 Setup Log Files” and “Start SQL Server Manually.”

I have also checked admin permissions settings all seems to be fine. also i have installed the same sql server on some other identical machine, which was successfully installed.

please guide how to solve this issue. thank YOu.

converting varchar to date/Using isdate()

I have a flat file that I am importing into a SQL Server 2005 staging table as character data.

I need to convert the birthday field to datetime format when copying it to the final destination table. I was doing so using the following:

BIRTHDAY = case when isdate(DOB)=1 then convert(datetime, '19'+right(DOB, 2)+left(DOB, 2)+substring(DOB,3,2)) else null end

The problem is only 100+ of the birthdays from the 32k+ file are identified as dates.

I cannot see a difference between the ones that are dates and the ones that aren't. I have included a sampling below.

good date   bad date
41129   100465
10531   122467
10429   20252
81030   62661
31231   20959
11028   91965
80928   60665

Why script doesn't work in SQL Server (2005, 2014, ...) the first time

I created a table Table1 in separate connection

CREATE TABLE [dbo].[Table1]
(
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Column1] [varchar](50) NULL,

    CONSTRAINT [PK_Table1] 
       PRIMARY KEY CLUSTERED ([Id] ASC)
           WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, 
                 IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, 
                 ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

then I add rows in Column1 in a same connection

INSERT INTO [dbo].[Table9]([Column2])VALUES('abc')

After that, in other connection I try to add Column2 and update it

alter table Table1 
   add Column2 VARCHAR(20) NULL

update Table1 
set Column2 = 'a'

but get an error Invalid column name 'Column2'.

then trying add GO keyword

alter table Table1 add Column2 VARCHAR(20) NULL
go
update Table1 set Column2='a'

and get a success message (1 row(s) affected)

when I drop column Column2 and trying execute non workable script block from point 2 without keyword GO

alter table Table1 add Column2 VARCHAR(20) NULL
update Table1 set Column2='a'

I get a success message (1 row(s) affected)

Why ?

vendredi 8 janvier 2016

multiple column values on same row

I have a situation where I have to return owners of stores. Some have multiple owners and some do not. Rather than usual results:

>     RANK STORE# STORE NAME                 OWNER SS  LAST NAME   FIRST NAME OWNER SHARE
    >     1    123456 LUK OIL                    111223333 SMITH       JOHN       1
    >     1    987654 A LITTLE BIT OF EVERYTHING 222334444 JONES       WILLIAM    40
    >     2    987654 A LITTLE BIT OF EVERYTHING 333445555 DANIELS     SCOTT      60
    >     1    456789 GRIFFEY LIQUORS            444556666 GRIFFEY     KEN        51
    >     2    456789 GRIFFEY LIQUORS            555667777 PIAZZA      MIKE       49
    >     1    654321 QUICK STOP DELI            666778888 HALLADAY    ROY        100
    >     1    124578 WINE COUNTRY               777889999 FITZPATRICK RYAN       100
    >     1    895623 WAWA                       888990000 MARTIN      CURTIS     100

I need it to look like the following:

RANK    STORE#  STORE NAME               OWNER SS     LAST NAME FIRST NAMEOWNER SHARE OWNER SS2 LAST NAME2 FIRST NAME2  
1 123456    LUK OIL                          111223333    SMITH          JOHN      1
1 987654    A LITTLE BIT OF EVERYTHING       222334444    JONES          WILLIAM   40 333445555 DANIELS     SCOTT                        
1 456789    GRIFFEY LIQUORS                  444556666    GRIFFE         KEN       51 555667777 PIAZZA      MIKE
1 654321    QUICK STOP DELI                  666778888    HALLADAY       ROY       100
1 124578    WINE COUNTRY                     777889999    FITZPATRICK    RYAN      100
1 895623    WAWA                             888990000    MARTIN         CURTIS    100

I have tried using CTEs, and temp tables but I cannot filter the data by rank to put into two different tables before selecting. I am drawing a blank.

jeudi 7 janvier 2016

Moving records from SQL Server 2014 to 2005 database

I have 917419 records in a table in a SQL Server 2014 database. I want to move theses records into a SQL Server 2005 database.

I have generated script into a file using "generate and publish wizard" for one table, and I ran the script file into command prompt by using

sqlcmd -U sa -P abc123* -S XXX\SQL2014 -i E:\script.sql -o E:\Scriperror.txt

It executed successfully. Only 915419 records are inserted into SQL Server 2005 database. The remaining 2000 records are missing.

Also we have compared the both records in excel and we inserted missing records manually. Our client want to move data to SQL Server 2005 every two months. So comparison and manual insert is not possible.

Can anyone help me why the 2000 records are missing? Which is the best way to resolve this problem?

merge Store proc with datatype conversions

I am able to execute my storeproc. When I execute it second time instead of updating the existing values same values from source are inserted as new values. i.e my target has 1 2 3 When I run the store proc sec time instead of updating 1,2,3 it is inserting the same 1 2 3 1 2 3 My condition for when matched then select S.REPORT_TEST1 except T.REPORT_TEST1 is not working. When I use the same code on a different table which doesn't have data conversions I am able to update. Can anyone tell where am I going wrong.

CREATE PROCEDURE [dbo].[Merge]

    INSERT INTO .[dbo].[TARGET]      
               (      REPORT_TEST1
                     ,REPORT_TEST2
             ,REPOST_TEST3

                       FROM 
              (
        MERGE [dbo].[TARGET] T
        USING 
        (
            SELECT
              Cast([REPORT TEST1] as int)   [REPORT_TEST1]
                     ,Cast([REPORT TEST2] as int)   [REPORT_TEST2]
             ,Cast([REPORT TEST3] as int) [REPORT_TEST3]    

            FROM [dbo].[SOURCE]

                ) S
            ON 
            (T.[REPORT_TEST1]=S.[REPORT_TEST1]

             )

                    WHEN NOT MATCHED BY TARGET
                  THEN INSERT                 

                   VALUES (
                    S.REPORT_TEST1
                               ,S.REPORT_TEST2
                                   ,S.REPOST_TEST3
                                               )

              WHEN MATCHED
            AND EXISTS 
                  (
                SELECT 
                    S.REPORT_TEST1
                               ,S.REPORT_TEST2
                        S.REPOST_TEST3

                       EXCEPT
                SELECT   
                  T.REPORT_TEST1
                             ,T.REPORT_TEST2
                     ,T.REPOST_TEST3
                                  ) 


                  OUTPUT $ACTION ACTION_OUT
                    S.REPORT_TEST1
                   ,S.REPORT_TEST2
               ,S.REPOST_TEST3
                 ) 


     ;

Thanks

How can I insert result from stored procedure to a new table?

I have a SP that returns a SELECT (can't convert it into a view because it does a little bit more than a SELECT). I want to put the result into a new non temporary table.

So far this is what I've tried

select * into newTable from (StoredProcedure) t

But it returns me

Incorrect syntax near ')'.

MSSQL bulkcopy insert million records is slow

I have a table with 1 million records. I need to be able to move those records to another database and another table. I'm using a stored proc to get the data. It fills a data adapter it then bcp's the data into the new table.

We're on SQL 2005 and C# 4. we will be moving to SQL 2012 or 2014 and Studio 2015 with C# 4.6 or 5.0 If there are any functions that would make this work well.

for 10k records the process takes less than 1 second for 500k records, the dataadapter runs out of memory and the process fails. batching to 100k records, the select statement is the issue in SQL returning 100k records at a time takes 2 minutes per loop.

Is there a way, or what is wrong with my code below to keep the data adapter from being filled and instead map the columns and have BulkCopy stay server side and just push the records from the db to the new table like maybe SSIS? IT seems the bulk copy itself is lightning fast, but the adapterfill fails because it runs out of memory trying to populate the adapter with 1 million records. Without doing 1 row at a time, i'd just like to move the data between tables. one table has 27 columns with 5 of the columns not being in table 2 which has 32 columns and some columns are not named the same in both tables.

This is a Proof of Concept (PoC).

                sourceConn_transDB.Open();
                SqlCommand sourceCommand = new SqlCommand(queryString, sourceConn_transDB);
                DataTable table = new DataTable();

                sourceCommand.CommandTimeout = 600;

                using (var adapter = new SqlDataAdapter(sourceCommand))
                {
                    WriteLineWithTime("Adapter Fill");
                    adapter.Fill(table);
                }

                if ((table == null) || (table.Rows.Count <= 0))
                    break;

                using (SqlBulkCopy bulk = new SqlBulkCopy(targetConn_reportDB, SqlBulkCopyOptions.KeepIdentity, null) { DestinationTableName = "PatientEvent" })
                {
                    bulk.ColumnMappings.Add(new SqlBulkCopyColumnMapping("PatientID", "PatientID"));
                }

How to ensure non-null duplicate values are not inserted in SQL Server 2005

I have a history database in SQL Server 2005 that is used to archive data from live database. I need to add a column in history database named RowID INT. This column cannot be made as identity since it need to store values from live database.

Note: In the live database the RowID is identity column. This column was added by me in live database also recently.

I need to make sure that in history database, the non-null values inserted into this column is unique. I understand that in SQL Server, we cannot make a nullable column as unique.

So, in SQL Server 2005, what is the most efficient way to make sure that insertion of non-null duplicate values into RowID columns throws an error?

How to skip the first and consider the second row whenever duplicate cells come in a column SQL Server

I have the following table. The startdatetime column is repeated when the duration is over a day. What I want is to write a query which skips the first row and count the difference of the second row whenever a duplicate cell in a startdatetime column come. E.g. In the case of following sample table the output I want is given in the table.

CREATE TABLE TEST
    ([Name] varchar(50), [StartDateTime1] datetime, [EndDateTime2] datetime, Diffy int)
;

INSERT INTO Test
    ([Name], [StartDateTime], [EndDateTime2], [Diffy])
VALUES
    ('ABC', '2015-07-21 16:08:02.000', '2015-07-21 16:18:10.000', '608' ),
    ('ABC', '2015-07-21 16:18:10.000', '2015-07-21 23:06:46.000', '24516' ),
    ('ABC', '2015-07-21 16:18:10.000', '2015-07-23 12:37:35.000', '159565' ),
    ('ABC', '2015-07-23 17:33:35.000', '2015-07-24 11:07:00.000', '63205' )
;


╔══════╦════════╗
║ Name ║ Diffy  ║
╠══════╬════════╣
║ ABC  ║    608 ║
║ ABC  ║ 159565 ║
║ ABC  ║  63205 ║
╚══════╩════════╝

The simple query I used is

Select 
 Name,
 DateDiff(SECOND, StartDateTime, EndDateTime) As Diffy
From
 Test

Convert datetime to numeric

I am trying to take a date which is in a varchar column in a table, add 1 day to it, and set it as the value of a datetime variable. This is part of a process that runs daily and I need to make sure the day resets to one at the end of the month. Or at the end of the year it doesn't increase from 151231 to 151232. The problem I am having is converting @Date back to numeric in the form YYMMDD. For example VIRN_CHK = '151231', @Date as written below is 'Jan 1 2016 12:00AM'. I need to convert it to 160101 so I can save it in a column in another table of type numeric(6,0).

DECLARE @Date as datetime
set @Date = convert(varchar,dateadd(d, 1,(select top(1) VIRN_CHK from STAGE_INST)))
update cdcdatei
set OT_DATE = @Date

How to check if user 'sa' (SQL Server) is enable with vb.net

I would like to know if is possible to check if user 'sa' is enable (SQL Server 2005), but with vb.net.

I tried to find it with this query select * syslogins, but here I can´t find it.

Thanks advanced

sql server 2005 stored procedure takes 14 hours to complete

I have two stored procedures which runs to create reports, and however it takes around 14 hours to complete, which seems little odd to me. Any help will be appreciated

When we generate report it calls the stored procedure1 and stored procedure 1 calls stored procedure 2

the stored procedure 2 is taking around 12 hours to complete, which is as following

USE [OPICSTEST2]
GO
/****** Object:  StoredProcedure [dbo].[CreateWorkTablesForWCASRep2]    Script Date: 01/07/2016 09:16:46 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

--Check if SPSHSUM has at least 1 record in it
--if it doesnt drop the table as needs recreating

ALTER Procedure [dbo].[CreateWorkTablesForWCASRep2] as
--Add to SPSHUM table or build it from scratch THE SPSHSUM table 
--And the table exists
if exists (select * from INFORMATION_SCHEMA.TABLES where TABLE_NAME =
'SPSHSUM')
BEGIN
    DROP TABLE [dbo].[SPSHSUM]
END
    --IF the table does not exist create it
        CREATE TABLE [dbo].[SPSHSUM](
        [ARCDATE] [datetime] NULL,
        [BR] [char](2)  NULL,
        [CNO] [char](10)  NULL,
        [SECID] [char](20)  NULL,
        [CCY] [char](3)  NULL,
        [PORT] [char](4)  NULL,
        [COST] [char](10)  NULL,
        [SETTQTY] [decimal](38, 2) NULL,
        [SETTPRICE] [decimal](38, 8) NULL,
        [SETTAVGCOST] [decimal](38, 8) NULL,
        [SETTQTYYTD] [decimal](38, 2) NULL,
        [SETTPRICEYTD] [decimal](38, 8) NULL,
        [SETTAVGCOSTYTD] [decimal](38, 8) NULL,
        [REALIZEDGAIN] [int] NOT NULL,
        [OS] [decimal](38, 8) NULL,
        [OP] [decimal](38, 8) NULL,
        [CM] [decimal](38, 8) NULL,
        [PC] [decimal](38, 8) NULL,
        [SC] [decimal](38, 8) NULL
    ) 



--Create the @SPSHR Temp table that is required
DECLARE @SPSHR TABLE 
(SETTDATE datetime,
BR char(2),
CNO char(10),
SECID char(20),
CCY char(3),
PORT char(4),
COST char(10),
PS char(1),
ORIGQTY decimal(19,6),
COSTAMT decimal(19,6),
REVDATE datetime,
PRODTYPE CHAR(2) ,
VERDATE datetime)

insert into @SPSHR
(
SETTDATE ,
BR ,
CNO ,
SECID,
CCY,
PORT,
COST,
PS ,
ORIGQTY ,
COSTAMT,
REVDATE ,
PRODTYPE ,
VERDATE 
)
(
select  
SETTDATE,
BR ,
CNO ,
SECID,
CCY ,
PORT ,
COST ,
PS ,
ORIGQTY ,
COSTAMT ,
REVDATE ,
PRODTYPE ,
VERDATE 
from SPSH
WHERE PORT <>'CPTY'
AND VERDATE is not null and PRODTYPE ='EQ'
--hdb 28TH feb 08 REMOVING REVERSALS AND MAKING SP RECREATE EVERY DAY TO FIX PROBLEM OF REVERSALS INVALIDATING LOGIC
and REVDATE IS NULL
UNION ALL
select 
SETTDATE,
BR,
WCUS.CNO,
SECID,
CCY,
PORT,
COST,
case DR when 'D' then 'S' else 'P' end ,
QTY,
0,
REVDATE,
PRODTYPE as PRODTYPE,
VERDATE as VERDATE
from RDFH inner join WCUS on WCUS.COSTCENT =RDFH.COST
WHERE PORT <>'CPTY' and QTY<>0
AND VERDATE is not null and PRODTYPE ='EQ'
)


--if the table does not exist run this sql to create table

--run this whatever to pick up new securities
--if not exists (select * from INFORMATION_SCHEMA.TABLES where TABLE_NAME =
--'SPSHSUM')
--begin

--insert the header records
insert into SPSHSUM
select  
TMPTBL.ARCDATE as ARCDATE,
TMPTBL.BR as BR,
TMPTBL.CNO as CNO,
TMPTBL.SECID as SECID,
TMPTBL.CCY as CCY,
'CLIE' as PORT, --HDB hard coded to stop duplicates after change 25th Mar 08
TMPTBL.COST as COST,
TMPTBL.SETTQTY as SETTQTY,

--COSTAMT IS CHANGED TO SALECOST AND PURCHCOST DATE 16/05/2008
abs(case when TMPTBL.SETTQTY<0 then (TMPTBL.SALECOST)/TMPTBL.ORIGQTYSale else (TMPTBL.PURCHCOST)/TMPTBL.ORIGQTYPurch end )as SETTPRICE,
(case when TMPTBL.SETTQTY<0 then (TMPTBL.SALECOST)/TMPTBL.ORIGQTYSale else (TMPTBL.PURCHCOST)/TMPTBL.ORIGQTYPurch end )*TMPTBL.SETTQTY as SETTAVGCOST,

0 as SETTQTYYTD,
0 as SETTPRICEYTD,
0 as SETTAVGCOSTYTD,

--CHANGED TO 0 16/05/2008
--TMPTBL.SETTQTY*0 as SETTQTYYTD,
--abs(case when TMPTBL.SETTQTY<0 then (TMPTBL.COSTAMT)/TMPTBL.ORIGQTYSale else (TMPTBL.COSTAMT)/TMPTBL.ORIGQTYPurch end )*0 as SETTPRICEYTD,
--(case when TMPTBL.SETTQTY<0 then (TMPTBL.COSTAMT)/TMPTBL.ORIGQTYSale else (TMPTBL.COSTAMT)/TMPTBL.ORIGQTYPurch end )*TMPTBL.SETTQTY*0 as SETTAVGCOSTYTD,

--HDB 25thMar08 
CASE when PORT = 'RFDF' THEN
0
ELSE
CASE WHEN (ABS(PURCHCOST)>0 AND ABS(SALECOST)>0) THEN 
    case when ABS(PURCHCOST)>ABS(SALECOST) then
    (((PURCHCOST/ORIGQTYPurch)*ORIGQTYSale)-SALECOST)
    else
        case when ABS(PURCHCOST)=ABS(SALECOST) then
        COSTAMT
        ELSE
    (((SALECOST/ORIGQTYSale)*ORIGQTYPurch)- PURCHCOST) 
    END
    end
ELSE 0 END 
END
as REALIZEDGAIN,
ORIGQTYSale as OS,
ORIGQTYPurch as OP,
COSTAMT as CM
,PURCHCOST as PC
,SALECOST as SC
from 
    (
    select 
        SETTDATE as ARCDATE
        ,BR as BR
        ,CNO as CNO
        ,SECID as SECID
        ,CCY as CCY
--HDB 25thMar08 
        ,PORT as PORT
        ,COST as COST
       ,sum(case PS when 'S' then (ORIGQTY) else (ORIGQTY*-1) end)  as SETTQTY 
       ,SUM(case PS WHEN 'S' then (ORIGQTY) else 0 end) as ORIGQTYPurch
       ,SUM(case PS WHEN 'P' then (ORIGQTY*-1) else 0 end) as ORIGQTYSale
      ,SUM(case when REVDATE  is null  
                then (case PS WHEN 'S' then COSTAMT else 0 end) 
                else (case PS WHEN 'S' then (COSTAMT*-1) else 0 end) 
                end) as PurchCOST
      ,SUM(case when REVDATE  is null  
                then (case PS WHEN 'P' then COSTAMT else 0 end )
                else (case PS WHEN 'P' then (COSTAMT*-1) else 0 end)
                end) as SaleCOST
      ,SUM(COSTAMT) as COSTAMT
    from @SPSHR SPSHR
    where 
    --only for days before the current branch processing date
    SETTDATE<(SELECT BRANPRCDATE from BRPS where BRPS.BR =SPSHR.BR) and
    PRODTYPE ='EQ' and
--Remove Port out of join HDB --25th Mar 08 HDB 
    SPSHR.SETTDATE=(select MIN(SETTDATE) from @SPSHR b where b.Br=SPSHR.BR and b.CNO =SPSHR.CNO and  b.SECID =SPSHR.SECID  and b.COST =SPSHR.COST)
    and SPSHR.REVDATE is null
    and SPSHR.VERDATE is not null
    group BY SPSHR.SETTDATE,SPSHR.BR,SPSHR.CNO,SPSHR.SECID,SPSHR.CCY,SPSHR.COST,SPSHR.PORT
    ) as TMPTBL
where 
not exists (select 'x' from SPSHSUM SS where TMPTBL.BR =SS.BR and TMPTBL.SECID = SS.SECID and TMPTBL.CNO =SS.CNO) 
--where the record does not exist in SPSHSUM


--If the table exists run for each date in turn insert into
declare @tmpx as int

set @tmpx = -1

while (@@rowcount>0 or @tmpx=-1)
BEGIN

   set @tmpx = 1
    insert into SPSHSUM select 
    TMPTBL.ARCDATE as ARCDATE,
    TMPTBL.BR as BR,
    TMPTBL.CNO as CNO,
    TMPTBL.SECID as SECID,
    TMPTBL.CCY as CCY,
    'CLIE' as PORT,
    TMPTBL.COST as COST,
    (sum(TMPTBL.SETTQTY)+
    max(SPSHSUM.SETTQTY)) as SETTQTY,
    max(abs(
    case when SPSHSUM.SETTQTY<0 then
        (case when (TMPTBL.SETTQTY + SPSHSUM.SETTQTY)<0 then (SPSHSUM.SETTAVGCOST + SALECOST)/(SPSHSUM.SETTQTY+TMPTBL.ORIGQTYSale) 
         else (PURCHCOST)/TMPTBL.ORIGQTYPurch end 
        )
    else
        (case when (TMPTBL.SETTQTY+ SPSHSUM.SETTQTY)<0 then (TMPTBL.SALECOST)/TMPTBL.ORIGQTYSale 
        else (SPSHSUM.SETTAVGCOST+TMPTBL.PURCHCOST)/(SPSHSUM.SETTQTY+TMPTBL.ORIGQTYPurch) end 
        )
    end
    ))
     as SETTPRICE,

    max((TMPTBL.SETTQTY+SPSHSUM.SETTQTY) 
    *
    abs(
    case when SPSHSUM.SETTQTY<0 then
        (case when (TMPTBL.SETTQTY + SPSHSUM.SETTQTY)<0 then (SPSHSUM.SETTAVGCOST + SALECOST)/(SPSHSUM.SETTQTY+TMPTBL.ORIGQTYSale) 
         else (PURCHCOST)/TMPTBL.ORIGQTYPurch end 
        )
    else
        (case when (TMPTBL.SETTQTY+ SPSHSUM.SETTQTY)<0 then (TMPTBL.SALECOST)/TMPTBL.ORIGQTYSale 
        else (SPSHSUM.SETTAVGCOST+TMPTBL.PURCHCOST)/(SPSHSUM.SETTQTY+TMPTBL.ORIGQTYPurch) end 
        )
    end
    ))
        as SETTAVGCOST,
    max(SPSHSUM.SETTQTY) as SETTQTYYTD,
    max(SPSHSUM.SETTAVGCOST) as SETTAVGCOSTYTD,
    max(SPSHSUM.SETTPRICE) as SETTPRICEYTD,

--HDB 25thMar08 
sum(CASE when TMPTBL.PORT = 'RFDF' THEN
0
ELSE
    (case when SPSHSUM.SETTQTY<0 then
            case when (ABS(ORIGQTYPurch)<abs(ORIGQTYSale+ SPSHSUM.SETTQTY)) then 
                    --SPREAD
                        --Sale Cost
                        (((SETTAVGCOST+SALECOST) / (SPSHSUM.SETTQTY + ORIGQTYSale)) 
                        --Purchase COST
                        - (case when ORIGQTYPurch =0 then 0 else (TMPTBL.PurchCOST / ORIGQTYPurch) end))
                    --END SPREAD
                    --* Volume
                    * abs(ORIGQTYPurch)

                 else
                    --SPREAD
                        --Sale Cost
                        (((SETTAVGCOST+SALECOST) / (SPSHSUM.SETTQTY + ORIGQTYSale)) 
                        --Purchase COST
                        - (case when ORIGQTYPurch =0 then 0 else (TMPTBL.PurchCOST / ORIGQTYPurch) end))
                    --END SPREAD
                    * abs(ORIGQTYSale + SPSHSUM.SETTQTY)
                 end

         else 
            case when (abs(ORIGQTYSale)<abs(ORIGQTYPurch + SPSHSUM.SETTQTY)) then 
                    --SPREAD
                        --Sale Cost
                        (
                        (case when ORIGQTYSale=0 then 0 else (SALECOST / ORIGQTYSale) end)
                        --Purchase COST
                        - (case when (SPSHSUM.SETTQTY + ORIGQTYPurch) = 0 then 0 else ((SETTAVGCOST+PURCHCOST) / (SPSHSUM.SETTQTY + ORIGQTYPurch)) end)
                        )
                    --END SPREAD
                    --* Volume
                    * abs(ORIGQTYSale)

                 else

                    --SPREAD
                        --Sale Cost
                        (
                        (case when ORIGQTYSale=0 then 0 else (SALECOST / ORIGQTYSale) end)
                        --Purchase COST
                        - (case when (SPSHSUM.SETTQTY + ORIGQTYPurch) = 0 then 0 else ((SETTAVGCOST+PURCHCOST) / (SPSHSUM.SETTQTY + ORIGQTYPurch)) end)
                        )
                    --END SPREAD
                    --* Volume
                    * abs(SPSHSUM.SETTQTY+ORIGQTYPurch)

                 end

         end 

    )  END)
     as REALIZEDGAIN,

    sum(ORIGQTYSale),
    sum(ORIGQTYPurch),
    sum(COSTAMT) as CM
    ,sum(PURCHCOST) as PC
    ,sum(SALECOST) as SC
    from 
        --Temp table inside sql
        (
        select 
            SETTDATE as ARCDATE
            ,BR as BR
            ,CNO as CNO
            ,SECID as SECID
            ,CCY as CCY
            ,PORT as PORT
            ,COST as COST
           ,sum(case when REVDATE is null 
                then (case PS when 'S' then ORIGQTY else (ORIGQTY*-1) end)
                else (case PS when 'S' then (ORIGQTY*-1) else ORIGQTY end)
                end)  as SETTQTY 
           ,SUM(case when REVDATE  is null  
                then (case PS WHEN 'S' then ORIGQTY else 0 end) 
                else (case PS WHEN 'S' then (ORIGQTY*-1) else 0 end) 
                end) as ORIGQTYPurch
           ,SUM(case when REVDATE  is null  
                then (case PS WHEN 'P' then (ORIGQTY*-1) else 0 end )
                else (case PS WHEN 'P' then ORIGQTY else 0 end)
                end) as ORIGQTYSale

           ,SUM(case when REVDATE  is null  
                then (case PS WHEN 'S' then COSTAMT else 0 end) 
                else (case PS WHEN 'S' then (COSTAMT*-1) else 0 end) 
                end) as PurchCOST
           ,SUM(case when REVDATE  is null  
                then (case PS WHEN 'P' then COSTAMT else 0 end )
                else (case PS WHEN 'P' then (COSTAMT*-1) else 0 end)
                end) as SaleCOST
           ,SUM(case when REVDATE  is null 
                then COSTAMT
                else (COSTAMT*-1)
                END) as COSTAMT

        from @SPSHR SPSHR
        where
        PRODTYPE ='EQ' and VERDATE is not null and
        --only for days before the current branch processing date
        SETTDATE<(SELECT BRANPRCDATE from BRPS where BRPS.BR =SPSHR.BR) and
--Remove Port out of join HDB --25th Mar 08 HDB
        SETTDATE=(select MIN(SETTDATE) from @SPSHR b where b.Br=SPSHR.BR and b.CNO =SPSHR.CNO and  b.SECID =SPSHR.SECID  --and b.PORT =SPSHR.PORT
        --Get the min settlement date that has not already been added to the new table ie bigger than the max 
--Remove Port out of join HDB --25th Mar 08 HDB
        and b.SETTDATE>(select max(ARCDATE) from SPSHSUM where b.Br=SPSHSUM.BR and b.CNO =SPSHSUM.CNO and  b.SECID =SPSHSUM.SECID and b.COST =SPSHR.COST
        )) OR
        --deal with reversals
--Remove Port out of join HDB --25th Mar 08 HDB
        SPSHR.REVDATE=(select MIN(SETTDATE) from @SPSHR b where b.Br=SPSHR.BR and b.CNO =SPSHR.CNO and  b.SECID =SPSHR.SECID  and b.COST =SPSHR.COST
        --Get the min settlement date that has not already been added to the new table ie bigger than the max 
        and b.SETTDATE>(select max(ARCDATE) from SPSHSUM where b.Br=SPSHSUM.BR and b.CNO =SPSHSUM.CNO and  b.SECID =SPSHSUM.SECID
        ))

        group BY SETTDATE,BR,CNO,SECID,CCY,PORT,COST
        ) as TMPTBL, SPSHSUM 
    where 
     TMPTBL.Br=SPSHSUM.BR and TMPTBL.CNO =SPSHSUM.CNO and  TMPTBL.SECID =SPSHSUM.SECID  and
    --Max record in the SPSHSUM table
--Remove Port out of join HDB --25th Mar 08 HDB
    SPSHSUM.ARCDATE =( Select MAX(C.ARCDATE) from SPSHSUM C where C.BR=SPSHSUM.BR and C.CNO =SPSHSUM.CNO and  C.SECID =SPSHSUM.SECID  and C.COST =SPSHSUM.COST)
    group by 
    TMPTBL.ARCDATE,
    TMPTBL.BR,
    TMPTBL.CNO,
    TMPTBL.SECID,
    TMPTBL.CCY,
    TMPTBL.COST
END

Group and Stuff multiple rows based on Count condition

I have a script that runs every 10 minutes and returns table with events from past 24 hours (marked by the script run time)

ID      Name                TimeOfEvent                 EventCategory       TeamColor
1       Verlene Bucy        2015-01-30 09:10:00.000         1                   Blue
2       Geneva Rendon       2015-01-30 09:20:00.000         2                   Blue
3       Juliane Hartwig     2015-01-30 09:25:00.000         3                   Blue
4       Vina Dutton         2015-01-30 12:55:00.000         2                   Red
5       Cristin Lewis       2015-01-30 15:50:00.000         2                   Red
6       Reiko Cushman       2015-01-30 17:10:00.000         1                   Red
7       Mallie Temme        2015-01-30 18:35:00.000         3                   Blue
8       Keshia Seip         2015-01-30 19:55:00.000         2                   Blue
9       Rosalia Maher       2015-01-30 20:35:00.000         3                   Red
10      Keven Gabel         2015-01-30 21:25:00.000         3                   Red

Now I'd like to select two groups of Names based on these conditions:

1) Select Names from same EventCategory having 4 or more records in past 24 hours.

2) Select Names from same EventCategory and same TeamColor having 2 or more records in past 1 hour.

So my result would be:

4+per24h: Geneva Rendon, Vina Dutton, Cristin Lewis, Keshia Seip        EventCategory = 2
4+per24h: Juliane Hartwig, Mallie Temme, Rosalia Maher, Keven Gabel     EventCategory = 3
2+per1h:  Rosalia Maher, Keven Gabel                                    EventCategory = 3, TeamColor = Red

For the first one, I have written this:

SELECT mt.EventCategory, MAX(mt.[name]), MAX(mt.TimeOfEvent), MAX(mt.TeamColor)
  FROM #mytable mt
GROUP BY mt.EventCategory
HAVING COUNT(mt.EventCategory) >= 4

because I don't care for the actual time as long as it's in the past 24 hours (and it always is), but I have trouble stuffing the names in one row.

The second part, I have no idea how to do. Because the results need to have both same EventCategory and TeamColor and also be limited by the one hour bracket.

mercredi 6 janvier 2016

grouping the record basis of different criteria

I have table like bellow how to write a workable code.

code    type    date        amount  qty
2001    Advance 1/1/2015    200     0
3001    Advance 2/5/2015    0       0
2001    Balance 12/30/2015  500     1
3001    Balance 5/5/2015    200     1
3002    Advance 1/3/2015    100     0

I need to select only the item with it's balance received and total amount also need to show in full like:

code    type    date        totalamount qty
3001    closed  5/5/2015    200         1
2001    Closed  12/30/2015  700     `   1

Error starting at BEGIN of WHILE LOOP in SQL Server 2005

I get an error message every time I run a WHILE loop code (in Oracle SQL Developer 2005). I got the following code from online examples and the error seems to occur at Line 4 which is where the "BEGIN" statement is.

-- DECLARE @intFlag int
    SET @intFlag = 1
    WHILE (@intFlag <=5)
    BEGIN
     PRINT @intFlag
    SET @intFlag = @intFlag + 1
    IF @intFlag = 4
    BREAK;
    END
    GO

Error message:

Error starting at line 4 in command:
    BEGIN
     PRINT @intFlag
    SET @intFlag = @intFlag + 1
    IF @intFlag = 4
    BREAK;
    END
    GO
    Error report:
    [Microsoft][ODBC Microsoft Access Driver] Invalid SQL statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'.

What could be causing this error? Should I be using a different way to implement the WHILE loop?

mardi 5 janvier 2016

selecting unique records monthly basis

I have one table, records like

id      date       branch
1001    01/01/2015  VBR
1002    02/05/2015  CBR
1001    03/01/2015  VBr
1005    05/05/2015  CBR
1005    12/12/2015  VBR
1006    05/05/2015  CBR

I need to select records monthly wise (date wise) but it should be unique, otherwise it should not be in any other month eg: if I select month 5/2015 it should return 1006

lundi 4 janvier 2016

Replicating data from 2014 to 2005 - tempoary soltuion

I will be installing a new database sql 2014 system, which is based on our current 2005 database system. The new system will be on a completely new infrastructure when we go live, leaving the current infrastructure available for rollback should we encounter any issues.

The business requires that a rollback option be available for 2 weeks minimum. Therefore in the event of a disaster scenario we would be required to switch back to the 2005 database system. So the challenge I have is replicating the data upon going live with the 2014 database system.

I am looking for a way to replicate the data (not necessarily the schema) from the 2014 system to the 2005 system.

I am not really a fan of SQL Server Replication and my preference is not to use this. My understanding is that this is not an option for us anyway due to the versions being too far apart, and therefore not supported.

I want to reach out to the community to find out if any tools are available to achieve this type of replication. It may be possible for us to implement a schema change freeze if this helps in finding the right solution.

Please can you advise what options are available to us, if any? Or should we look to develop a bespoke system internally?

Are you aware of any Microsoft partners that might achieve this for us through a solution already developed?

Thanks in advance for any advice.

Joe

SQL command from variable in SSIS Dataflow task

An existing SSIS package has Data source with Data access mode: SQL command from variable. User variable is having select statement as value. Now I added a column to select statement in variable and saved the package. This new column is not showing up in data source columns list. Tried closing the package and reopening it, on doing this I no longer see the new column in variable value select statement too. Looking for solutions other than creating a new variable and calling it in data source.

can we implement innerjoin in the following sql query

CREATE TABLE forgerock (id INT, [date] DATETIME, empcode INT,[file] VARCHAR);
INSERT INTO forgerock
VALUES
    (1, '2015-12-31 01:20:02', 56, 'abc1'),
    (2, '2016-01-01 01:20:02', 58, 'abc2'),
    (3, '2016-01-02 01:20:02', 46, 'abc3'),
    (4, '2016-01-03 01:20:02', 16, 'abc4'),
    (5, '2016-01-04 01:20:02', 36, 'abc5');

CREATE TABLE forge (empcode INT, [user_name] VARCHAR);
INSERT INTO forge
VALUES
    (56, 'ram'),
    (58, 'ram1'),
    (46, 'ram2'),
    (16, 'ram3'),
    (36, 'ram4');

this are my table.i try to print the file name and user_name from the tables with respect to current date and the day before the current date

i tried the query

ResultSet resultset = statement.executeQuery("select file  from forgerock where '"+date+"' >= CURRENT_DATE('"+date+"', INTERVAL 1 DAY);") ;

but i got the exception

Incorrect syntax near the keyword 'CURRENT_DATE'.

how can i print the file and user_name with respect to DATETIME(current date and day before the current date)

How to convert string date in BST and GMT format to SQL Server format as date type

I imported a table into SQL Server 2014 and I found that the date format is in BST and GST format. I want to create a view and change the whole column to SQL Server date type to perform operations. I don't mind truncating the time section.

Wed Apr 07 00:00:00 BST 1943
Tue Jan 08 00:00:00 GMT 1985

I was able to do it in Excel with the following formula but want to do it in SQL Server:

=IFERROR(DATEVALUE(MID(E2,9,2)&"-"&MID(E2,5,3)&"-"&RIGHT(E2,4)), "")

All I am looking for is

1983-08-04

retrieve data based on derived column

How to rewrite the bellow code as working sql. I need to retrieve 'item' from another table based on my new 'newcol' the code is. select s.code,o.[work name],case when o.[work name] is null then s.code else o.[work name] end newcol,item=(select item from table1 where table1.code=newcol) from shoplog s left outer join odc o on o.barcode=s.code

vendredi 1 janvier 2016

Want to print todays date with month and year

I want to get today's Month and date by the below query, but I am getting something as

Jul 21 1905 12:00AM

I want it as

Dec 31 2015

below is my query

declare @actualMonth int 
  declare @actualYear int
set  @actualYear = 2015
set @actualMonth = 12
 DECLARE @DATE DATETIME
SET @DATE = CAST(@actualYear +'-' + @actualMonth AS datetime) 
 print  @DATE

what is wrong here

[SqlException (0x80131904): Adding a value to a 'datetime' column caused overflow.]

I think this error is coming because of the dateadd() function but im not sure. Can someone help me toi identify the issue and resolve it. I have casted to a particular date because it is the requirement for the report for which i have written this sp. Please help

ALTER PROCEDURE [dbo].[sp_SelectAllTrackingDetails]
@StrSearch AS VARCHAR(200) = ' CAST(L.NewDate AS datetime) >= CAST(''03/15/2008'' AS datetime)'
AS
CREATE TABLE #TempLeads(Date Datetime,LeadId INT)
INSERT INTO #TempLeads
SELECT DateSubmitted,UID 
FROM WebPageDataCollection.dbo.HomeOwnerwebdata2 
WHERE CAST(DateSubmitted AS datetime) >= CAST('03/15/2008' AS datetime)

EXEC('SELECT L.NewDate      
, (SELECT COUNT(DISTINCT JOBUID) FROM tblLeadTrackingLog AS LTL WITH (NOLOCK) INNER JOIN #TempLeads TL WITH (NOLOCK) ON LTL.JobUid = TL.LeadId AND DATEDIFF(DD,L.NewDate,TL.Date)=0 WHERE (CONVERT(varchar(10),  LTL.InsertDate, 101) = L.NewDate) AND LTL.LeadStatus=1) AS Generated       
, (SELECT COUNT(DISTINCT JOBUID) FROM tblLeadTrackingLog AS LTL WITH (NOLOCK) INNER JOIN #TempLeads TL WITH (NOLOCK) ON LTL.JobUid = TL.LeadId AND DATEDIFF(DD,L.NewDate,TL.Date)=0 WHERE (CONVERT(varchar(10),  LTL.InsertDate, 101) = L.NewDate) AND LTL.LeadStatus=3) AS Matched  
, (SELECT COUNT(DISTINCT JOBUID) FROM tblLeadTrackingLog AS LTL WITH (NOLOCK) INNER JOIN #TempLeads TL WITH (NOLOCK) ON LTL.JobUid = TL.LeadId AND DATEDIFF(DD,L.NewDate,TL.Date)=0 WHERE (CONVERT(varchar(10),  LTL.InsertDate, 101) = L.NewDate) AND LTL.LeadStatus=4) AS Notified  
, (SELECT COUNT(DISTINCT JOBUID) FROM tblLeadTrackingLog AS LTL WITH (NOLOCK) INNER JOIN #TempLeads TL WITH (NOLOCK) ON LTL.JobUid = TL.LeadId AND DATEDIFF(DD,L.NewDate,TL.Date)=0 WHERE (CONVERT(varchar(10),  LTL.InsertDate, 101) = L.NewDate) AND LTL.LeadStatus=5) AS Accepted  
, (SELECT COUNT(DISTINCT JOBUID) FROM tblLeadTrackingLog AS LTL WITH (NOLOCK) INNER JOIN #TempLeads TL WITH (NOLOCK) ON LTL.JobUid = TL.LeadId AND DATEDIFF(DD,L.NewDate,TL.Date)=0 WHERE (CONVERT(varchar(10),  LTL.InsertDate, 101) = L.NewDate) AND LTL.LeadStatus=6) AS Rejected  
, (SELECT COUNT(DISTINCT JOBUID) FROM tblLeadTrackingLog AS LTL WITH (NOLOCK) INNER JOIN #TempLeads TL WITH (NOLOCK) ON LTL.JobUid = TL.LeadId AND DATEDIFF(DD,L.NewDate,TL.Date)=0 WHERE (CONVERT(varchar(10),  LTL.InsertDate, 101) = L.NewDate) AND LTL.LeadStatus=12) AS Scheduled  
, (SELECT COUNT(DISTINCT JOBUID) FROM tblLeadTrackingLog AS LTL WITH (NOLOCK) INNER JOIN #TempLeads TL WITH (NOLOCK) ON LTL.JobUid = TL.LeadId AND DATEDIFF(DD,L.NewDate,TL.Date)=0 WHERE (CONVERT(varchar(10),  LTL.InsertDate, 101) = L.NewDate) AND LTL.LeadStatus=7) AS PreBidsPlaced  
, (SELECT COUNT(DISTINCT JOBUID) FROM tblLeadTrackingLog AS LTL WITH (NOLOCK) INNER JOIN #TempLeads TL WITH (NOLOCK) ON LTL.JobUid = TL.LeadId AND DATEDIFF(DD,L.NewDate,TL.Date)=0 WHERE (CONVERT(varchar(10),  LTL.InsertDate, 101) = L.NewDate) AND LTL.LeadStatus=8) AS PreBidsRejected  
, (SELECT COUNT(DISTINCT JOBUID) FROM tblLeadTrackingLog AS LTL WITH (NOLOCK) INNER JOIN #TempLeads TL WITH (NOLOCK) ON LTL.JobUid = TL.LeadId AND DATEDIFF(DD,L.NewDate,TL.Date)=0 WHERE (CONVERT(varchar(10),  LTL.InsertDate, 101) = L.NewDate) AND LTL.LeadStatus=9) AS BidsPlaced  
, (SELECT COUNT(DISTINCT JOBUID) FROM tblLeadTrackingLog AS LTL WITH (NOLOCK) INNER JOIN #TempLeads TL WITH (NOLOCK) ON LTL.JobUid = TL.LeadId AND DATEDIFF(DD,L.NewDate,TL.Date)=0 WHERE (CONVERT(varchar(10),  LTL.InsertDate, 101) = L.NewDate) AND LTL.LeadStatus=10) AS BidsRejected  
, (SELECT COUNT(DISTINCT JOBUID) FROM tblLeadTrackingLog AS LTL WITH (NOLOCK) INNER JOIN #TempLeads TL WITH (NOLOCK) ON LTL.JobUid = TL.LeadId AND DATEDIFF(DD,L.NewDate,TL.Date)=0 WHERE (CONVERT(varchar(10),  LTL.InsertDate, 101) = L.NewDate) AND LTL.LeadStatus=11) AS FeedBackReceived  
, (SELECT COUNT(DISTINCT JOBUID) FROM tblLeadTrackingLog AS LTL WITH (NOLOCK) INNER JOIN #TempLeads TL WITH (NOLOCK) ON LTL.JobUid = TL.LeadId AND DATEDIFF(DD,L.NewDate,TL.Date)=0 WHERE (CONVERT(varchar(10),  LTL.InsertDate, 101) = L.NewDate) AND LTL.LeadStatus=2) AS Deleted  
FROM      
(SELECT ROW_NUMBER() OVER (ORDER BY UID) AS RowNumber      
, CONVERT(varchar(max), DATEADD(dd, 1 - (ROW_NUMBER() OVER (ORDER BY UID)), GETDATE()), 101) AS NewDate      
FROM tblLeadTrackingLog) AS L      
WHERE ' + @StrSearch +  ' ORDER BY L.NewDate DESC') -- CAST(L.NewDate AS datetime) >= CAST('03/06/2008' AS datetime)

How to calculate working days including time in SQL Server 2005

To simplify for the various time zones, we are going to use GMT time to determine when the weekend starts and ends.

Weekend will start on Saturday 00:00 GMT and end on Monday 00:00 GMT, regardless of what OU/time zone the user is working from.

So taking the example above, instead of taking 2.75 days for the E2E cycle time, it would be .75 days, as it would be 8 hours on Friday + 10 hours on Monday = 18 hours (or .75 days)

How do I calculate this in SQL Server?