Transact SQL :: Recursive Top 100 Rows

Nov 6, 2015

I need limit on recursion. I have a recursion query. which gives me a parent child record set. I want my application to fetch only top 100 rows. In those 100 rows the parent child set should not get break. Even if it gives 105 rows also fine but it should have entire parent child structure.

If you see my below table. where null is the table which dont have parents but have the child.

ITEMID parentItemid
6 NULL
7 NULL
8 6
9 7
12 NULL
13 12
14 8
16 6
17 16

And it is temp table #test1and my recursive query.

;WITH Cte AS
(
SELECT ItemID,ParentItemID,CAST(ItemID AS VARCHAR(200)) [path] FROM #Test1 WHERE ParentItemID IS NULL
UNION ALL
SELECT t.ItemID,t.ParentItemID, CAST([path]+'.'+CAST(t.ItemID AS VARCHAR(20)) AS VARCHAR(200)) FROM Cte c JOIN #Test1 t ON C.ItemID=t.ParentItemID
)
SELECT * FROM Cte ORDER BY path ASC

Here how can i get top 100 parent child set. 

View 4 Replies


ADVERTISEMENT

Transact SQL :: Types Don't Match Between Anchor And Recursive Part In Column ParentID Of Recursive Query

Aug 25, 2015

Msg 240, Level 16, State 1, Line 14

Types don't match between the anchor and the recursive part in column "ParentId" of recursive query "tmp". Below is query,

DECLARE @TBL TABLE (RowNum INT, DataId int, DataName NVARCHAR(50), RowOrder DECIMAL(18,2) NULL, ParentId INT NULL)
INSERT INTO @TBL VALUES
(1, 105508, 'A', 1.00, NULL),
(2, 105717, 'A1', NULL, NULL),
(3, 105718, 'A1', NULL, NULL),
(4, 105509, 'B', 2.00, NULL),
(5, 105510, 'C', 3.00, NULL),
(6, 105514, 'C1', NULL, NULL),

[code]....

View 2 Replies View Related

Transact SQL :: Recursive CTE Work Flow

May 7, 2015

how recursive CTE works...Synthesise table with non-recursive CTE

;WITH Employee (ID, Name, MgrID) AS
(
SELECT 1, 'Keith', NULL UNION ALL
SELECT 2, 'Josh', 1 UNION ALL
SELECT 3, 'Robin', 1 UNION ALL
SELECT 4, 'Raja', 2 UNION ALL

[code]....

the first part query will return one row
IDNameMgrIDnLevelFamily
1KeithNULL11

then this result set using after union all query .how the level + 1 condition is working ?  and how its return values .

View 7 Replies View Related

Transact SQL :: Recursive CTE To Fetch Parent

May 20, 2015

I am using the following code to get the next immediate parent of a customer in the hierarchy and it works fine. However, it works only for one customer at a time (i made this a scalar function and I pass the customer id as shown below).

How can I modify this so that i can get each customer and its next immediate parent (all of them in one shot in a single data set)?

WITH my_cte (CustomerID, ParentID, Level)
AS
(
SELECT CustomerID, ParentID, 0 AS Level
FROM [dbo].MyTable
WHERE CustomerID = @CustomerID

UNION ALL
SELECT CustomerID, ParentID, Level + 1
FROM [dbo].MyTable e
INNER JOIN my_cte AS cte ON e.CustomerID = cte.ParentID
)

select CustomerID from my_cte WHERE Level <> 0 AND Level = (SELECT MIN(Level) FROM my_cte WHERE Level <> 0)

View 14 Replies View Related

Transact SQL :: Recursive Query To Assign Values

Jul 30, 2015

I'm trying to find it difficult to use recursice CTEs or better solution for a special request below. There are two tables 1) @sizes serves as a lookup or reference for right drive and 2) @test is sample data with different sizes. Assume that I want to evenly distribute the drive letters from table1 to table2 by checking the size available.

E.g.: for the first record in  @test; id = 1 where the size is 50 and it fits in Y: drive -- left over space in Y: = 50

id=2, size 2.5, space available from left over = 50 - 2.5 = 47.5 which again fits into Y:
id = 3, size 51, cannot in fit in Y: drive as there is enough space in Y: to allocate (51 > 47.5)

so pick the next drive check on availability again

DECLARE @sizes TABLE (id TINYINT, size DECIMAL(5,2), drive VARCHAR(3))
INSERT INTO @Sizes
SELECT 1,100.00,'Y:'
UNION ALL
SELECT 2,80.85,'Z:'

[Code] ....

-- My output should look like

col1  ,  val ,   path
A          50      Y:
B           2.5    Y:
C          51     Z:
D          2.6    Y:
E          52      Z:
F           2.7    Y:

View 5 Replies View Related

Transact SQL :: Recursive CTE Parent Child Query

Oct 31, 2015

I have a Recursive CTE for TFS database which gives me below results:

Parent (User Story) level 0
             -------------.Task(Dev) and ask(QA) --

level  1
    BUG level 2
                ---------------Task (Dev) and Task(QA)
level2 

So, My ParentID column keeps two ParentId one for User story which keeps the child tasks and child bugs and another for Bug Child tasks

I need to update this results and want to see all of the tasks under User story so the result I want is:

User Story:

 Task(dev and QA)
 Task (Dev and QA ) but its should know that these tasks are the bug tasks.

View 10 Replies View Related

Transact SQL :: Recursive Query To Find Child Of A Parent Until Last Leaf

Oct 22, 2015

I need to write recursive query to find child of a parent until the last leaf. Below is my code. 

;WITH Parent AS(
SELECT [ParentID],Value
FROM[DynamicColsValues_TP1]
WHEREValue IS null
UNION ALL
SELECT t1.[ParentID],T1.Value, FROM DynamicColsValues_TP1 t1 INNER JOIN Parent t2
ON t1.[ParentID]=t2.[ParentID]
)
SELECT * FROM Parent option (maxrecursion 0)

When I execute this code. It is returning me millions of rows. Whereas  i have only 20 rows in a table max 40 rows it should return.

View 7 Replies View Related

How To Convert Recursive Function Into Recursive Stored Procedure

Jul 23, 2005

I am having problem to apply updates into this function below. I triedusing cursor for updates, etc. but no success. Sql server keeps tellingme that I cannot execute insert or update from inside a function and itgives me an option that I could write an extended stored procedure, butI don't have a clue of how to do it. To quickly fix the problem theonly solution left in my case is to convert this recursive functioninto one recursive stored procedure. However, I am facing one problem.How to convert the select command in this piece of code below into an"execute" by passing parameters and calling the sp recursively again.### piece of code ############SELECT @subtotal = dbo.Mkt_GetChildren(uid, @subtotal,@DateStart, @DateEnd)FROM categories WHERE ParentID = @uid######### my function ###########CREATE FUNCTION Mkt_GetChildren(@uid int, @subtotal decimal ,@DateStart datetime, @DateEnd datetime)RETURNS decimalASBEGINIF EXISTS (SELECTuidFROMcategories WHEREParentID = @uid)BEGINDECLARE my_cursor CURSOR FORSELECT uid, classid5 FROM categories WHERE parentid = @uiddeclare @getclassid5 varchar(50), @getuid bigint, @calculate decimalOPEN my_cursorFETCH NEXT FROM my_cursor INTO @getuid, @getclassid5WHILE @@FETCH_STATUS = 0BEGINFETCH NEXT FROM my_cursor INTO @getuid, @getclassid5select @calculate = dbo.Mkt_CalculateTotal(@getclassid5, @DateStart,@DateEnd)SET @subtotal = CONVERT (decimal (19,4),(@subtotal + @calculate))ENDCLOSE my_cursorDEALLOCATE my_cursorSELECT @subtotal = dbo.Mkt_GetChildren(uid, @subtotal,@DateStart, @DateEnd)FROM categories WHERE ParentID = @uidENDRETURN @subtotalENDGORod

View 4 Replies View Related

Transact SQL :: Table Trigger To Delete All Rows Before Inserting Rows

Jul 24, 2015

I have a SQL script to insert data into a table as below:

INSERT into [SRV1INS2].BB.dbo.Agents2
select * from [SRV2INS14].DD.dbo.Agents

I just want to set a Trigger on Agents2 Table, which could delete all rows in the table , before carry out any Insert operation using above statement.I had below Table Trigger on [SRV1INS2].BB.dbo.Agents2 Table as below: But it did not perform what I intend to do.

USE [BB]
GO
/****** Object:  Trigger    Script Date: 24/07/2015 3:41:38 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON

[code]....

View 3 Replies View Related

Transact SQL :: Selecting Rows As Column Name And Other Column Values As Rows

Jun 25, 2015

I have questions and answers from one table, I need to select questions as column names and answers column values as the results for the questions column.

View 28 Replies View Related

Transact SQL :: How To Merge Two Rows Into One Row

Sep 24, 2015

I have a table that has columns like following

trans_code
gl_code
12qw3
a1235
12qw3
a6578
12qw3
t531
e34g6
gt25
e34g6
y7327
e34g6
v23409

Is there an easy way to turn this into format below ??

trans_code
gl_code_1
gl_code_2
12qw3
a1235
a6578
12qw3
a1235

[code]....

View 5 Replies View Related

Transact SQL :: Merging Every 3 Rows Into A Single Row

Aug 18, 2015

I have 2 columns (ID, Msg_text) in a table where i need to combine every 3 rows into single row. What would be the best option i have? I know by using 'STUFF' and 'XML PATH' i can convert all the rows into a single row but here i'm looking for every 3 rows into a single row.

View 3 Replies View Related

Transact SQL :: Convert Rows Into Columns?

Oct 8, 2015

How can I convert the following data

Create Table tbl_Customer_Bank_Details
(
[CustomerID] int,
[CustomerName] varchar(50),
[AccountType] varchar(50),
[BankAccountNo] varchar(50)
)

[Code] ...

into the following format

Create Table tbl_Customer_Bank_Details2
(
[CustomerID] int,
[CustomerName] varchar(50),
[AccountType] varchar(50),
[BankAccountNo1] varchar(50),

[Code] ....

I am looking at this [URL]

how to do this in SQL 2000.

View 16 Replies View Related

Transact SQL :: How To Get Max Date And All Rows Data

Oct 17, 2015

i have this table the TDate in string (not date)

MEN
===
id       |      Name    |      TDate
1        |   aa           |       01.05.2015
2        |   bb           |       05.05.2015

View 6 Replies View Related

Transact SQL :: Combine Two Rows To One Without XML Path

Aug 13, 2015

I have one table list this

declare @test table(Id int, Description varchar(500))
insert into @test
values (1, '<b>Name :</b> XUZ <br/><br/>'),
       (1, '<b>Type : </b> QWE <br /><br/>'),
  (2, '<b>Name : </b> ABC <br /><br/>'),
  (2, '<b>Type : </b> FGH <br /><br/>')

My expected result is 

1, '<b>Name :</b> XUZ <br/><br/> <b>Type : </b> QWE <br /><br/>'
2, '<b>Name : </b> ABC <br /><br/> <b>Type : </b> FGH <br /><br/>'

As you can see its combine two rows of data group by id. Issue is If I use for xml path('') then its replace my html tags <b> to like <b> so after that then I again i need to replace all these symbols. Is it possible to get expected result without using xml path or if we use xml path then still my html tag leave as it is.

View 5 Replies View Related

Transact SQL :: Convert Rows To Columns?

Apr 24, 2015

i have a table with dob and test results , i am trying to pull the data from the table and converting rows columns , below is the table i am using . i used to pivot to do this .

create table #TEST_RESULTS
(ID INT,NAME VARCHAR(10),DOB DATETIME,DAYS_SINCE_BIRTH_TO_TEST INT,TEST_RESULTS INT )
INSERT INTO #TEST_RESULTS
VALUES(1,'A','2015-01-01' , 0 ,1)
,(1,'A','2015-01-01' , 0 ,1)
,(1,'A','2015-01-01' , 1 ,3)
,(1,'A','2015-01-01' , 2 ,6)

[code]...

View 9 Replies View Related

Transact SQL :: How To Compare Rows With Spaces

Nov 17, 2015

I would like to compare rows from 2 tables.

For ex:

Table1
Col1 Col2 Col3
1      a     aa
2      b     bb

Table2
Col1 Col2 Col3
1        a   aa
2      b     bb

Notice Table2.Col2 first row has an extra space " a", where Table1.Col2 value is "a".I need to compare all the columns, not just 1 column (any of the column can be different). Do we use CHECKSUM for this, or is there a better way to compare the 2 tables (in this case resulted in Table2 row 1 col 2 being the difference ?

View 10 Replies View Related

Transact SQL :: Concatenate Description In 2 Rows

Oct 7, 2015

 I have a requirement .Where i might have multiple rows one of the row will have description and second row might be related description but wiht routning number null .I want to concatenate these rows

Id
Routingnum
Ddesc
1
101
A

[code]....

View 8 Replies View Related

Transact SQL :: How To Retrieve Affected Rows

Aug 31, 2015

I have a database table where upon inserting a new record, I get 1 row(s) affected twice. But when deleting the record, I only get one instance of that message. I'm not really an expert, neither have I designed the database, but how can I retrieve the actual affected rows or determine what table does the other row pertain to?

View 2 Replies View Related

Transact SQL :: SUM Of Multiple Rows With Where And Group By

Apr 30, 2015

I have a table Transaction that looks something like the following :

TransactionID          

Currency        Credit             Debit
1     USD      500               0
2     Afcu          6000              0

[Code] ....

I write query like this

select SUM(credit)-SUM(Debit)as [Balance] ,Source from Transaction group by Source

And it came like

Balance Source           
1500                        USD
6000                        Afcu
6800                        INR
7000                        Pfc
-200                         AUD

But I also want to add  Afcu , Pfc with USD and  want output like

Balance Source
14500                        USD
6800                          INR
-200                           AUD

View 3 Replies View Related

Transact SQL :: Find Combination Of Rows?

May 10, 2015

I have this data as below. I need to find out the combination from the data and take a count of them

CREATE TABLE A
(    nRef INT,
     nOrd     INT,
     Token     INT,
     nML              INT,
     nNode            INT,
 sSymbol          VARCHAR(50),
 nMessageCode     INT
)
INSERT INTO A
(   nReferenceNumber,nOrderNumber,nTokenNumber,nML,nNode,sSymbol,nMessageCode )
VALUES
(1, 101, 1001,0,2,'SILVER',13073),

[code]....

if you can see, the rows with column nRefNo 1 and 3 are same i.e. with same combination of Symbol viz. Silver and Castorseed. How to get this combination together and then take count of them. Please note i will be dealing with more than 5 million rows.

View 6 Replies View Related

Transact SQL :: Clone Some Rows On Selection

Apr 20, 2015

I have a table in which I have defined 2 columns. First column is called 'name' and second is called 'number'.It looks like sample bellow:

Name        |    Number        |
---------------------------------
John          |    2                  |
Jessica       |    3                  |
Jack           |    2                  |
etc...

I need to make a query that will have the following results:

Name   |
----------
John     |
John     |
Jessica  |
Jessica  |
Jessica  |
Jack     |
Jack     |

John for 2 rows, Jessica for three rows and Jack for two rows. Is it possible only with loops or is there in SQL a duplicate/clone function...?

View 3 Replies View Related

Transact SQL :: Find How Many Rows Replicated

Aug 20, 2015

How Do we find how many ROWS REPLICATED to subscriber at specific interval ?

View 3 Replies View Related

Transact SQL :: How To Number Rows In SELECT

Oct 8, 2015

I have a SELECT statement with multiple JOINs. I want to number the rows returned by this SELECT statement. What's the easiest way to do this?

My current SELECT statement returns this:

ProjectId -- TaskId -- TaskName
123  - 111 -- Do something
123  - 222 -- Do something else
123  - 333 -- Do one more thing

I want to return this:

ProjectId -- TaskId -- TaskName -- Sequence
123  - 111 -- Do something  -- 1
123  - 222 -- Do something else  -- 2
123  - 333 -- Do one more thing  -- 3

View 2 Replies View Related

Transact SQL :: Where Condition - If No Input Value Select All Rows

Apr 27, 2015

I  have table with filed

EmpProject -Table
Empno, Name, Project NO, cost center

I need to restrict the results by project No by user input. In case if user did not provide any value for the projectNO, then need to fetch all rows.

Select empno, name, projecno, cost_center from empproject where projectno=nvl(:pno, :deptno)

View 6 Replies View Related

Transact SQL :: Add Group Number To Similar Rows?

Jun 9, 2015

How can I add a group number to the following query?

For example, I want to be able to have all rows that have Category = 'Field Sales' and Division = 'CA BDM' to be given a unique group number (GN):

RN                   ReportDate Category                       Division                       TotalBalance
-------------------- ---------- ------------------------------ ------------------------------ ---------------------
1                    2015-06-08 Field Sales                    CA BDM                         299743154.3912
2                    2015-06-07 Field Sales                    CA BDM                         299765954.0354
3                    2015-06-01 Field Sales                    CA BDM                         297902654.4172
1                    2015-06-08 Key Accounts                   Life Office                    49954981.74
2                    2015-06-07 Key Accounts                   Life Office                    50016989.22
3                    2015-06-01 Key Accounts                   Life Office                    50169967.26
4                    2015-05-31 Key Accounts                   Life Office                    50169918.01

Becomes

GN   RN                   ReportDate Category                       Division                TotalBalance
-------------------------- ---------- ------------------------------ ------------------------------ ---------------------
1      1                    2015-06-08 Field Sales                    CA BDM                     299743154.3912
1      2                    2015-06-07 Field Sales                    CA BDM                     299765954.0354
1      3                    2015-06-01 Field Sales                    CA BDM                     297902654.4172
2      1                    2015-06-08 Key Accounts                   Life Office                    49954981.74
2      2                    2015-06-07 Key Accounts                   Life Office                    50016989.22
2      3                    2015-06-01 Key Accounts                   Life Office                    50169967.26
2      4                    2015-05-31 Key Accounts                   Life Office                    50169918.01

i.e. each combination of Category+Division results in a new GN.

The query is:

selectROW_NUMBER() over (partition by Category, Division order by ReportDate desc) 'RN'
, ReportDate
, Category
, Division
, sum(BalanceGBP) as 'TotalBalance'
FROM FlowsAndOpenings
group by ReportDate, Category, Division
order by Category, Division, RN

View 2 Replies View Related

Transact SQL :: Bulk Insert 0 Rows Affected

May 15, 2015

I have a file which has some wind data that i am trying to import into a sql data base through bulk insert. if the script works as it supposed i should see 144 rows impacted but i see 0 rows affected. 

BULK INSERT TOWER.RAWINTERFACE_1058 FROM 'C:Temp900020150427583.txt' 
WITH(CHECK_CONSTRAINTS,CODEPAGE='RAW',DATAFILETYPE='char',FIELDTERMINATOR=' ',ROWTERMINATOR='
',FIRSTROW=172)

The code works if the file is large but if its small 0 rows are affected. and also if i remove the header rows then the file works again. want to understand what is going on here. i am including the screen shot of the file in notepad++. I have tried changing the row terminator to ' ' , ' ' and also tried to change the codepage but nothing seems to work. No error file is being generated either, if i give a error file option. 

View 7 Replies View Related

Transact SQL :: Total Count Of Table Rows

Sep 15, 2015

I have a question regarding the total count of the table rows

Select count (name) from test. Lets say I have got 200 count. And Select count (lastname) from test1.I have got 200.And this counts I should store it in "There are nn name items awaiting your attention and nn pending lastname's awaiting your approval".

So now I have to store the count in 'nn'.

View 5 Replies View Related

Transact SQL :: Filter - Join Query Rows

Nov 14, 2015

Please refer to the below query. I want to filter inner join rows based on outer query column value (refer to bold text).

SELECT M.MouldId, SI.StockCode, MI.Cavity, MI.ShotCounter, CQ.SumOfCastedQty  as CastedQty, MI.CounterStartup 
FROM        MouldItem MI
JOIN (SELECT JD.MouldId, JC.StockCode, SUM(JS.CastedQty) AS SumOfCastedQty
FROM JobCasting AS JS INNER JOIN JobCreationDet AS JD ON JS.JobDetId = JD.Uniid INNER JOIN JobCreation AS JC ON JD.JobIdx = JC.Uniid

[Code] ....

View 2 Replies View Related

Transact SQL :: How To Break Rows Into Multiple Columns

Jul 14, 2015

I have a table with 100 rows, 1 field (ID), and I would like to write a query to output it as 4 rows, and 25 columns.

Row data
ID
1
2
3
4
5
6
7
8
9
...
98
99
100

Output will be like
c1  c2   c3    c4    c5....
1    5    9      13
2    6    10    14
3    7    11    15
4    8    12    16

View 4 Replies View Related

Transact SQL :: Inventory Difference Between Rows Between Stores

May 8, 2015

how to measure a change in inventory over various stores.  My sql2008R2 express db gets a new row of data everyday from each store(about 40 stores) for a single product stock count "OnHand" and if there is any new stock on order.  When the new stock arrives it is added to the "OnHand" count.   I want to measure the delta change per day,per store.  I'm stuck on how to separate the stores and how to query the delta of stock.My data base looks like this
                               
TimeStamp Store
OnHand OnOrder
2015/04/22 18   1 - Concord
12
     0
2015/04/23 11   1 - Concord
11
 
[code]....

View 17 Replies View Related

Transact SQL :: Remove Blank Rows From Table?

Apr 17, 2012

I have a table for example like following

DECLARE @tmpTable table
(
name varchar(10),
address1 varchar(10),
phnno varchar(10),
mobno varchar(10)
)
INSERT INTO @tmpTable(name,address1,phnno,mobno)

[Code] ....

I want to remove all empty rows like row 1,2 and 3 in the above example.

I can't check all columns null values as there are many columns in my actual table.

View 6 Replies View Related

Transact SQL :: Based On One Column Need To Cascade Rows One By One

Sep 23, 2015

Here's the my structure and data as follows

>
SELECT tranno ,mrno medrecno ,createdon,createdat,no_of_trans nooftrans 
FROM mytab WHERE mrno = 'MR1514' and tranno = 1111
ORDER BY no_of_trans
tranno medrecno
createdon createdat
nooftrans

[Code] ...

Now requirement is : -

tranno medrecno
createdon createdat
nooftrans     tranno medrecno
createdon createdat
nooftrans

[Code] ....

View 4 Replies View Related







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