T-SQL (SS2K8) :: Identifying Current Record

Mar 6, 2014

I have a snapshot table of about 15 million records in the form of:

InvoiceIDLineItemIDSnapshotDateAmount
1 1 20140101 12
1 2 20140102 14
1 3 20140103 17
2 1 20140101 10
2 2 20140102 5
1 2 20140105 15
1 3 20140105 20

I want to create an additional column called Current as shown below:

InvoiceIDLineItemIDSnapshotDateAmount Current
1 1 20140101 12 1
1 2 20140102 14 0
1 3 20140103 17 0
2 1 20140101 10 1
2 2 20140102 5 1
1 2 20140105 15 1
1 3 20140105 20 1

How can we write a query to achieve this while keeping in mind:

- We do not want to do unnecessary record lookups and Updates
- We only update records that corresponds to new entries. For example, we should not touch the record for InvoiceID = 2 in the above example

View 6 Replies


ADVERTISEMENT

Identifying Bad Record And Field Value

Nov 14, 2006

To All:

I'm importing a data file of 600,000 records. Some records contain bad data.

What's the best way to identify the text file row and field that caused my package to bomb AT THE TIME IT bombs?



Thanks,

r

View 1 Replies View Related

T-SQL (SS2K8) :: Identifying Active Linked Servers

Aug 27, 2014

I am performing analysis of linked servers across 2000-2008R2 and need to find/build a list of linked servers that are truly active. For the sake of the post let's define 'active' have executed a distributed query in the last 5 days.

I have been scanning the DMVs without much success. Perhaps I must look more closely at MSDTC?

The end result would be to cleanup 300+ linked servers across 40+ SQL Servers.

View 4 Replies View Related

T-SQL (SS2K8) :: Identifying Potential Duplicate Records In A Given Table?

Oct 8, 2015

any useful SQL Queries that might be used to identify lists of potential duplicate records in a table?

For example I have Client Database that includes a table dbo.Clients. This table contains various columns which could be used to identify possible duplicate records, such as Surname | Forenames | DateOfBirth | NINumber | PostalCode etc. . The data contained in these columns is not always exactly the same due to differences caused by user data entry; so some records may have missing data from some of the columns and there could be spelling differences too. Like the following examples:

1 | Smith | John Raymond | NULL | NI990946B | SW12 8TQ
2 | Smith | John | 06/03/1967 | NULL | SW12 8TQ
3 | Smith | Jon Raymond | 06/03/1967 | NI 99 09 46 B | SW12 8TQ

The problem is that whilst it is easy for a human being to review these 3 entries and conclude that they are most likely the same Client entered in to the database 3 times; I cannot find a reliable way of identifying them using a SQL Query.

I've considered using some sort of concatenation to a new column, minus white space and then using a "WHERE column_name LIKE pattern" query, but so far I can't get anything to work well enough. Fuzzy Logic maybe?

the results would produce a grid something like this for the example above:

ID | Surname | Forenames | DuplicateID | DupSurname | DupForenames
1 | Smith | John Raymond | 2 | Smith | John
1 | Smith | John Raymond | 3 | Smith | Jon Raymond
9 | Brown | Peter David | 343 | Brown | Pete D
next batch of duplicates etc etc . . . .

View 7 Replies View Related

How Do I Pass A Value In The Next Record To The Current Record?

Sep 20, 2007

Hey Forum,
Below is a solution for passing a previous value (Height) to the current record in a view using two related tables (Plant= ID PK and plantHeight = ID FK) However, I was wondering how I could also do the reverse, that is, pass a next value to the current record.

View 2 Replies View Related

T-SQL (SS2K8) :: Add Balance Of Previous Row To Current Row

Jul 2, 2014

I am novice to intermediate writer of T-SQL. Here is my current Query:

SELECT [FISCALYEAR],
[ACCTPERIOD],
SUM([ACTIVITYDEBIT]) AS TrialBalanceDebit,
[POSTINGTYPE]
FROM [dbo].[TB_Lookup]
WHERE [POSTINGTYPE]='Profit & Loss'
GROUP BY [FISCALYEAR],[ACCTPERIOD], [POSTINGTYPE]
ORDER BY acctperiod ASCand this is what is produces.

FISCALYEARACCTPERIODTrialBalanceDebitPOSTINGTYPE
2014 201401 282361372.13000 Profit & Loss
2014 201402 227246272.86000 Profit & Loss
2014 201403 315489534.33000 Profit & Loss
2014 201404 287423793.76150 Profit & Loss
2014 201405 256521290.76000 Profit & Loss
2014 201406 65582951.30000 Profit & Loss

Now I need a way to add another field that takes the TrialBalanceDebit from current ACCTPERIOD and adds it to the Previous ACCTPERIOD TrialBalanceDebit.

View 9 Replies View Related

T-SQL (SS2K8) :: How To Get Current Date Between Last 24 Hours

Jan 14, 2015

I have a query that will go into an ssis package (eventually). The package will run every night at 3am. I need to capture the last 24 hours of by using something like:

SELECT worktype, changedate, woclass
where siteid = 'GTM' and woclass = 'WORKORDER' and istask = 0
[highlight=#ffff11]and changedate between '2015-01-13 03:00:00' and '2015-01-14 03:00:00'[/highlight]

I know I am not doing the between correctly to get the changedate between the last 24 hours. Is there a way to correct this so that I am only getting the change date that is between 3am today and 3am yesterday on any given day I happen to run this?

View 7 Replies View Related

T-SQL (SS2K8) :: Set Current Row Using Values In Previous Row

Feb 25, 2015

I've tried all sorts of code i.e. cross apply, running totals, etc. Cannot get this to work. I am trying to add a previous row value but only doing it for each group.

Source records
DECLARE @tbl table (Item int, Sequence int, StartTime datetime, Duration int)
INSERT INTO @tbl (Item,Sequence,StartTime, Duration) VALUES (1,1,'2/25/2015 12:00 am',10),(1,2,null,20),(1,3, null,22),(2,1,'2/25/2015 1:00 am',15),(2,2,null,30),(2,3, null,45),(2,4, null,5)
select * from @tbl

ItemSequenceStartTimeDuration
1102/25/15 0:0010
12null 20
13null 22
2102/25/15 1:0015
22null 30
23null 45
2 4 null 5

I would like to set the start time of the next row to be equal to the previous row time + duration. I know the start time of each group of 'Items' when the 'Sequence' number = 1. The last 'duration' value in the group would be ignored.

My expected output would be:

ItemSequenceStartTimeDuration
1102/25/15 0:0010
1202/25/15 0:1020
1302/25/15 0:3022
2102/25/15 1:0015
2202/25/15 1:1530
2302/25/15 1:4545
2402/25/15 2:305

View 7 Replies View Related

Get Current Entered Record

Nov 20, 2007

Hi every one
I want to get the currently entered or updated record in the database table by using SQL Query or stored procedure.
 Thanx in advance
Take care
Bye

View 3 Replies View Related

Trigger - Current Record ?

Feb 5, 2004

CREATE TRIGGER test ON [Table_1]
FOR UPDATE
AS
UPDATE [Table_1]
set [Field_1] =SUSER_SNAME()

This trigger update all record, I want to update only the current record which is currenty update. How I cant to this ?

Sorry for my english

View 2 Replies View Related

T-SQL (SS2K8) :: Current Year Begin And End Dates

May 6, 2014

I am working on some payroll related code which currently has the following hard-coded CASE statement (I won't include the entire thing, it is lengthy):

AND b.TCDateTime BETWEEN '2013-01-01 0:00' and '2013-12-31 23:59'

I want to get rid of the hard coding, and have this use current year dates. So for 2014, it should reference rows where the TCDateTime is >='2014-01-01 0:00' AND <'2015-01-01 0:00'..I think the following would accomplish this, but would like confirmation that this is the 'best' way (and that it will work!)

SELECT CONVERT(DATETIME, CONVERT(CHAR(4), DATEPART(yyyy, GETDATE())) + '0101') AS curryrbegin
--output should be yyyy-01-01 00:00:00.0 where yyyy is current year
SELECT CONVERT(DATETIME, CONVERT(CHAR(4), DATEPART(yyyy + 1, GETDATE()))
+ '0101') AS nextyrbegin
--output s/b nextyear-01-01-00:00:00.0

Then, change the CASE statement to read:

AND (b.TCDateTime >= curryrbegin AND < nextyrbegin)

View 8 Replies View Related

T-SQL (SS2K8) :: Get Rows Based On Current Quarter

Sep 3, 2014

I am working on a report and the data source is Teradata. now I have situation where I want to get order id details based on the current quarter and year I am posting this same data. For TD related queries I do not where to post.

ACCT_ID ACCT_NMORD_NBRORD_DT ORD_AMT_USD
595709114ASDASD444447/28/2014 546
2224809440ASDASD444445/2/2012 546
1724031572ASDASD444446/22/2011 546
1702887651ASDASD444447/3/2014 546
1724020508ASDASD444447/16/2012 546
1148151895ASDASD444449/18/2013 546
2125154824ASDASD444449/2/2014 546
1503552723ASDASD4444412/20/2011 546
2224689808ASDASD4444410/4/2010 546
931387698ASDASD4444412/31/2010 546

View 4 Replies View Related

T-SQL (SS2K8) :: Winscp To Get Only Current Days Files?

Jan 21, 2015

I have to download the files from SFTP server, for which i am using WINSCP and i am able to successfully automate the process to download the files. But it is downloading all the files instead of only current day's files. Ihave searched for WINSCP documentation for time query parameter to pass to the get command. But its not working.

My source file name contains Datefield as "Filenameexample_150120_N001.txt".

Here 150120 mean Jan 20 2015.

Winscp has no functionality to query the files to parse using datefield. how to look for files which are from today's date.

Currently i am downloading files which contain *.* (meaning all files).

View 6 Replies View Related

How Do I Make Sure Only One Record Is The Current Issue?

Jun 22, 2007

I have a table of magazine issues. The table are defined as below:
issueID    int    Uncheckedname    varchar(50)    Uncheckedtitle    varchar(100)    Checkeddescription    varchar(500)    CheckedcrntIssue    bit    Checkedarchived    bit    CheckednavOrder    int    CheckeddateCreate    datetime    Checked
And here is what I want. Is there a way when inserting/updating or on the table itself to make sure that there is only one record that is marked as the current issue? The way I have it here in my table, any records can have the current issue (crntIssue) field checked. I only want one crntIssue field checked regardless of how many records or issues are in the table. If there is no way to automatically have SQL Server to manage that then that means I must check all the records before hand before the update/insert query, correct?

View 9 Replies View Related

SQL: UPDATE, DELETE Current Record Only

May 6, 2006

Well, I really messed up. Instead of changing the name of a current company record in a table I changed ALL the company names in the table. Me.CustomerDataSource.SelectCommand = "UPDATE tbl_customers SET company = '" & companyTextBox.Text & "'"
So, I need to insert a WHERE clause to fix this. My problem is that I've been searching everywhere for this simple command structure and cannot find anything that specifically addresses a simple way to reference the current record.
I tried...Me.CustomerDataSource.SelectCommand = "UPDATE tbl_customers SET company = '" & companyTextBox.Text & "' WHERE recno = @recno"
But I get the error:
Exception Details: System.Data.SqlClient.SqlException: Must declare the scalar variable "@recno".
Can anyone provide this simple query clause?

View 2 Replies View Related

Compare Previous To Current Record Row

Mar 3, 2014

My current code returns account_number with multiple start_date regardless of the value is same or not. However, I would like to get only the account number when the value on start_date is different within same account_number.

select
acct_number
count(start_date) from table_A
group by acct_number, start_date
having(count(start_date) > 1)

View 5 Replies View Related

T-SQL (SS2K8) :: Finding The Item Filled In Prior To Current One

May 13, 2015

I have data similar to the below

CREATE TABLE #TEMP
(
TYPE VARCHAR(10),
SEQ INT,
SUB_TYPE VARCHAR(10))

[Code] ....

Now for each type the seq is very important. Effectively by order of seq the subtype stays the same until another subtype changes it. So for TYPE1 100,110 and 150 are A. 170, 200,220 are B. 230 and 250 are C and so on.

However as you can see the data isnt actually stored in the row. I need a select statement that shows this data.

I have done this:

SELECT t1.*,t3.SUB_TYPE FROM #TEMP t1
CROSS APPLY
(SELECT MAX(SEQ) SEQ FROM #TEMP AS t2 WHERE t1.SEQ >= t2.seq AND t2.SUB_TYPE <>'' AND t1.TYPE = t2.TYPE
GROUP BY t2.TYPE) t2
INNER JOIN
#TEMP t3
ON t3.TYPE = t1.TYPE AND t2.SEQ = t3.SEQ

And it seems to work. Is this the easiest way to do it or am i missing something?

View 3 Replies View Related

How To Make A Trigger Refer To The Current Record

Jul 8, 2004

I have a table full of items that have a "date_updated" field. I'd like this field to be set to GETDATE() whenever a record is updated. I've got this trigger:

CREATE trigger tr_cp_shiptos_u on dbo.cp_shiptos for update as
update cp_shiptos set date_updated = GETDATE()

Problem is, of course, there's no WHERE clause..yet. I don't know how to refer to the record that was updated.... for example:

CREATE trigger tr_cp_shiptos_u on dbo.cp_shiptos for update as
update cp_shiptos set date_updated = GETDATE()
where shipto_id = @THIS_ID

I imagine there's some kind of builtin variable or something like that. How is this done?

Thanks in advance.

View 2 Replies View Related

How Do I Display Current SQL Server Record Number

Mar 21, 2008

Do anybody know how can I find or display to the current SQL server 2005 record number (eg. 10 of 1600) on a VB 2005 form label. The BindingNavigator on the form has been deleted. Thanks.

View 6 Replies View Related

T-SQL (SS2K8) :: Returning Results That Fall Within Current Financial Year?

Jun 3, 2014

I am using MSSQL Server 2008R2 and I am interested in returning rows from a 'financial' table that fall within the current year (each row contains a 'Entered Date'). I am located in Australia so my financial year consists of all entries between the date 01/07/xx to the 30/06/yy.

Perhaps using the datediff() function, or other functions as required to achieve what I need?

View 3 Replies View Related

T-SQL (SS2K8) :: Get Current DB Backup Setup List In Pivot Style?

Dec 1, 2014

I need to list the current DB Backup Set up list in PIVOT STYLE.

I need following way:

Database_NameFULL - DDIFF - ILOG - L
DB1DL
DB2D
modelDL
DB3DIL
msdbD

View 2 Replies View Related

T-SQL (SS2K8) :: Creating Database Where Each Record Is Required To Have Twin Record In Database

May 12, 2014

,I am creating a database where each record is required to have a twin record in the database.These is a type a value and a type b value and both must be present for the record to be valid.

Customer_ID, Order_Type, Product_Code
54, a, 00345
54, b, 00356

Is this something that would have to be done programmatically, or is it possible to create a constraint of some sort to ensure this?

View 8 Replies View Related

T-SQL (SS2K8) :: Table With Score Info For Groups - Ranking For Current And Previous Week

Jan 21, 2015

I have a table with score info for each group, and the table also contains historical data, I need to get the ranking for the current week and previous week, here is what I did and the result is apparently wrong:

select CurRank = row_number() OVER (ORDER BY cr.CurScore desc) , cr.group_name,cr.CurScore
, lastWeek.PreRank, lastWeek.group_name,lastWeek.PreScore
from
(select group_name,
Avg(case when datediff(day, asAtDate, getdate()) <= 7 then sumscore else 0 end) as CurScore

[Code] ....

The query consists two parts: from current week and previous week respectively. Each part returns correct result, the final merged result is wrong.

View 3 Replies View Related

SQL Server 2008 :: Count How Many Records Within 6 Months From Current Record Date

May 27, 2015

My data has 2 fields: Customer Telephone Number, Date of Visit.

Basically I want to add a field ([# of Visits]), which tells me what number of visit the current record is within 6 months.

Customer TN | Date of Visit | # of Visits (Within 6 month - 180 days)
1111 | 01-Jan-2015 | 1
1111 | 06-Jan-2015 | 2
1111 | 30-Jan-2015 | 3
1111 | 05-Apr-2015 | 4
1111 | 07-Jul-2015 | 3

As you can see, the last visit would counts as 3rd because 180 days from 07-Jul-2015 would be Jan-8-2015.

View 3 Replies View Related

T-SQL (SS2K8) :: Sorting Record By Use

Aug 5, 2014

I need to write SP which will call from front End to populate dropdown, But in dropdown uppermost value should be frequently used.

For example, My SP Select CountryID,Country Columns where i am displaying Country in dropdown. Now first time it will sort by ascending, next time if user selects US then US should be top and rest things after that.

Now If user selects Canada 3 times then result should sort as Canada,US, and rest countries.

if again US Selects 7 times then result should display as US,Canada,........

In short need to sort depending used previously. i.e. most popular first and so on......

View 6 Replies View Related

T-SQL (SS2K8) :: Query To Track Record?

Mar 14, 2014

I am having table which is having 5 columns say A,B,C,D and E. There are chances to change in C,D,E columns. I want to identify if any change happened in the above column and show to user prev value + new value.

i.e. i want to prepare query by using calculated extra 6 column where i want to put change happned in C,D,E columns.

how to do that?

View 5 Replies View Related

T-SQL (SS2K8) :: Selecting The Top Record With Certain Conditions?

May 14, 2014

The situation is that we have resources (trucks) that perform shifts. Shifts consists of actions. A resource can perform multiple shifts.

For every resource we want to find the record that:

- Is 'younger' than the last realized action.

- Has actionkind pickup, deliver or clean

I have constructed a solution with CTE and row_number but I was curious if there would be other alternatives. The fact that I'm joining a CTE onto itself and subject the outcome to a partition makes me think there are sharper ways.

Note that the action id in the data below is also sorted but in practice this need not be the case. The sorting key is prevalent.

output of the query is

id_action id_resource actionKindCode
4665 4 clean
34540 96 pickup
24000 901 clean
declare @mytable table (
id_action int,
id_shift int,

[code]....

View 6 Replies View Related

T-SQL (SS2K8) :: Making A Record Set Horizontal

May 14, 2014

I have a client with a fairly simple table as illustrated in my sample code. Their interesting requirement is that the records would be listed horizontally, end-to-end as I hope you can visualize based on what I'm providing here. Two other characteristics/specs of note, 1) there could be as few as two records end-to-end in a row or as many as 100 and 2) of course the column headings would have to be unique.

create table #tmpEndToEnd
(
ID int identity,
ClientID char(10),
Agency varchar(20),
Clinician varchar(20),
Goal varchar(50)

[code]....

View 3 Replies View Related

T-SQL (SS2K8) :: Calculating Average For Each Record

Jul 4, 2014

How to calculate Average sal foe below scenario.

I am having tables with 12 columns as jan,feb,.......dec.

Now I want to calculate average salary for each record, but condition is that if any month salary is zero then that column also exclude from average calculation.

For example : if jan and feb column values are zero then i want to calculate (mar+apr+...+dec)/10.

View 5 Replies View Related

T-SQL (SS2K8) :: Add Record And Commit Transaction

Oct 6, 2014

I am simply inserting records in a table, But if record already present then i dont want add that record and display resultset as -1.If record is not present then i want to add that record and commit transaction. I am doing like below : below is sample, I am considering only two columns.

CREATE PROCEDURE [dbo].[Sproc__Save_Teacher_Details]
-- Add the parameters for the stored procedure here
@FacilitiDetailID int
,@SpecialityType varchar(50)
AS
BEGIN

[code]....

above code is working fine for new recordset but if record exists then it is giving two resultsets -1 and 1, but i want to display only -1.

View 4 Replies View Related

T-SQL (SS2K8) :: Compare And Insert Record

Oct 15, 2014

I am having below two tables:

1) TableA : Which contains 5 columns(Column1,..........Column5)
2)TableB : Which contains 10 columns(Column1,..........Column10)

TableB contains millions of data.Now I want select all 5 columns from tableA but combination of Column1,Column2,Column3 if present in tableB, then i want exclude that records.I am doing as below:

select * from TableA a join TableB b a.column1!=b.column1 and a.column2!=b.column2 and a.column3!=b.column3 )

But query is taking almost 5 minutes. Is there is another approach?

View 4 Replies View Related

T-SQL (SS2K8) :: Display Record Using Group By?

Aug 3, 2015

I would like to display all the products with maximum SeqNo from the table below:

TABLE
ProductIDSeqNoBalance
111215
11135
111420
111510
12115
1212100
121325
121445

OUTPUT

ProductIDSeqNoBalance
111510
121445

View 3 Replies View Related

T-SQL (SS2K8) :: Selecting Latest Record With Info

Aug 27, 2014

I have created the following SQL snippet that is a very simple mock-up illustrating the problem (I hope!) that I am facing:

-- create table
if object_id('tempdb..#tmpdelnotes') is not null
drop table #tmpdelnotes

create table #tmpdelnotes(
DelNote int identity (1,1) ,
DelDate date not null,
Item int not null,
Customer int not null)

[code]...

What I need to retrieve is a unique list of item numbers with information about the latest (DelDate) delivery note. The "Clumsy workaround" works, but is not very pretty when doing multiple table joins. Is it really necessary to use a derived table for this kind of query? Window functions can only exist in the SELECT and ORDER BY clauses, which is understandable since the calculations take place (I would guess) after the aggregations in the HAVING clause.

View 2 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved