Nested Repeater Query
Mar 11, 2007
Hello Everyone,
I am trying to create a query for the purpose of a nested repeater relation. The information needs to be pulled from one table. I have shortened the columns to the ones that are required.
table - Pages
ID
PageName
ParentPageID
So, take the following example:
ID 14, PageName - Service A, ParentPage ID = 6
ID 15, PageName - Service B, ParentPage ID = 6
ID 36 PageName - Client 1, ParentPage ID = 14
ID 37 PageName - Client 2, ParentPage ID = 14
ID 38 PageName - Client 3, ParentPage ID = 15
ID 39 PageName - Client 4, ParentPage ID = 15
So, I want to create a query that will get my nested repeater to display as follows:
Service A
Client 1
Client 2
Service B
Client 3
Client 4
What I have come up with so far is:
SELECT * from tbl_Pages WHERE ParentPageID IN (Select ID From tbl_Pages)
SELECT p.ParentPageID, p.PageName, p.ID FROM tbl_Pages p
The relation would be based off ParentPageID. I keep getting errors that either there is no unique value or the relation is null. What am I am missing here?
View 5 Replies
ADVERTISEMENT
Oct 29, 2006
So I have code to fill my repeater with a data: Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim cnn As Data.SqlClient.SqlConnection = New Data.SqlClient.SqlConnection(System.Web.Configuration.WebConfigurationManager.ConnectionStrings("db_ConnStr").ConnectionString) Dim cmd1 As Data.SqlClient.SqlDataAdapter = New Data.SqlClient.SqlDataAdapter("SELECT aspnet_Users.UserName, COUNT(forum_posts.post_id) AS IlePost, forum_posts_1.post_content, forum_posts_1.topic_id, forum_posts_1.post_id, forum_posts_1.post_date FROM aspnet_Users INNER JOIN forum_posts ON aspnet_Users.uID = forum_posts.user_id INNER JOIN forum_posts AS forum_posts_1 ON aspnet_Users.uID = forum_posts_1.user_id GROUP BY aspnet_Users.UserName, forum_posts_1.post_content, forum_posts_1.topic_id, forum_posts_1.post_id, forum_posts_1.post_date HAVING (forum_posts_1.topic_id = @topic_id) ORDER BY forum_posts_1.post_date ASC", cnn) cmd1.SelectCommand.Parameters.AddWithValue("@topic_id", Request.QueryString("ID")) Dim ds As Data.DataSet = New Data.DataSet cnn.Open() cmd1.Fill(ds, "posts") Repeater1.DataSource = ds.Tables("posts") Page.DataBind() cnn.Close() End Sub And I want to take the value from column which I bolded - IlePost. I want take this out at compare with some condition. For example:Dim label as label = Repeater1.Findcontrol("Label1")If COLUMN < 10 thenlabel.text = "Less than 10"elselabel.text = "More than 10"I hope you understand me :-)
View 1 Replies
View Related
Nov 15, 2007
do i need to nest a query in RS if i want a calculated column to be compared against a multi value variable? It looks like coding WHERE calcd name in (@variable) violates SQL syntax. My select looked like
SELECT ... ,CASE enddate WHEN null then 1 else 0 END calcd name
FROM...
WHERE ... and calcd name in (@variable)
View 1 Replies
View Related
Sep 21, 2006
I'm new to ASP.NET and i've been banging my head aganist this problem for a few days now.I have a repeater and then a repeater inside that repeater. <asp:SqlDataSource ID="sqlRepeater1" runat="server" ConnectionString="<%$ ConnectionStrings:Inspections_DBCS %>" SelectCommand="SELECT count(*) as mycount FROM insuranceco with (NOLOCK) where insurancecoid=@insurancecoid" OnSelecting="sqlRepeater_Selecting" > <SelectParameters> <asp:Parameter DefaultValue='' Name="insurancecoid" Type="String" /> </SelectParameters> </asp:SqlDataSource> <% 'sqlRepeater1.SelectParameters["insurancecoid"].DefaultValue = "123"; %>This returns:Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. Compiler Error Message: BC30451: Name 'sqlRepeater1' is not declared.Source Error:Line 38: Line 39: <% Line 40: sqlRepeater1.SelectParameters["insurancecoid"].DefaultValue = "123";Line 41: %>Line 42: I tried a solution i saw on the web about using the onselecting event but that didn't pan out either Protected Sub sqlRepeater_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs) 'Handles sqlRepeater1.Selecting WithEvents 'Response.Write(e.Command.Parameters.Add) 'e.Command.Parameters.Add(e.Command.CreateParameter("P1", "test")) 'e.Command.Parameters.Add("P1", "value")I have to be doing something wrong because i would think there has to be a way to reference variables when you are going from repeater to repeater i just dont know.Please help my mask of sanity is starting to slip off.Thanks
View 4 Replies
View Related
May 25, 2008
Hi there,
In 2005.NET, if I used an asp:repeater, I would load the data from source and then manipulate it like so://load the data from source using a predefined connection and SQL Statement.private void LoadMyDataFromSource(){ try { connection.Open(); OleDbDataReader myReader = comm.ExecuteReader(); rptrCatList.DataSource = myReader; rptrCatList.DataBind(); myReader.Close(); } finally { connection.Close(); }} //catch the ItemDataBound event and manipulate the data how I wish before it's loaded into the Repeater.protected void rptrCatList_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { int title = 4; //this is the index of the column I wish to manipulate((Label)e.Item.FindControl("lblTitle")).Text = ((IDataRecord)e.Item.DataItem).GetString(title) + ":" } }This would give me all the flexbility I ever needed. But now I wish to use linq and since the IDataRecord relies on dataReader sources, I cannot obtain the same flexbility. Can anyone point me in the right direction for obtaining the same kind of flexbility but using a linq-to-SQL dataContext? I wish to manipulate mostData that comes through from my source, so: //loadng the data in via my linq-to-sql context.private void LoadProducts() { MyDataContext db = new MyDataContext (); var all = from p in db.Products_IncontinenceStandards where p.Product_Cat == "Category1" select p; rpterCat.DataSource = all; rpterCat.DataBind(); }This is where I get stuck because, even though I can still capture the ItemDataBound event since I have databound the Repeater to the linqSource, I can't access the individual fields (or this is what I think I can't do!), Does anyone know how to relate to this so I can create the same effect? Many Thanks,Nathan Channon
View 4 Replies
View Related
Sep 13, 2005
Hi,Please can somone help me with a nested SQL query. I have two tables please see belowTable 1CallIDEmployeeIDCallSummaryCallStatusTable 2CallHistoryIDCallIDDataAddedCallActionI would like to return the CallID, EmployeeID, CallSummary and CallStatus from Table 1, and also display the last CallAction from Table 2.This is a helpdesk database so a Call will have many CallActions i.e. Open, Held, Assigned Internal. How do I return the last CallAction Added against the selected CallID, I know I use the DateAdded but not sure about nested statements.The results I would like to return to the user would look like this:-Call ID: 1EmployeeID: 1Call Sumary: SQL ProblemCall Status: OpenCall Action (Last Action): Assigned Internal.
View 2 Replies
View Related
Oct 4, 1999
Hi,
I want to write one query which will select multiple distinct records from one table
For e:g
Lets say in a table i have 3 fields name,tel_no,sex
Now i want to list all the records which are distinct in each of these fields
like distinct name,distinct address
IS IT POSSIBLE and if yes HOW
Thanks
Ashish
View 1 Replies
View Related
Mar 2, 2004
I am having trouble with the following query.
Important Tables:
Product (table of products)
--ProductID
--ProductName
ProductCategories (Associates a Product with one or more categories)
--ProductID
--CategoryID
Category (table of categories that a product may fall under)
--CategoryID
--CategoryName
Information:
Basically I have a product that falls into two categories. Therefore there are two records in the ProcuctCategories Table. I am trying to create a query that will find all products that are in categories 1 & 2.
Attempted Solution:
SELECT * FROM Product
WHERE (ProductID IN (SELECT CategoryID FROM ProductCategories WHERE CategoryID =1))
AND
(ProductID IN (SELECT CategoryID FROM ProductCategories WHERE CategoryID =2))
This returned zero records though it should have returned the product that is in categories 1&2.
I would appreciate any help available.
Thank you,
-Patrick
View 2 Replies
View Related
Jul 20, 2005
HiI have 2 tables. The first has employee information and the second haspayroll information. I need to find out people who are not in thepayroll but in the employee table.Since the payroll has multiple instances i have to filter it and findout for each payroll.I don't think i have explained it very well so here is the data set.hope someone can help me with this.Thanks in advancepritTbl EmployeePlanIDSSN100111111111110012222222221001333333333TblPayrolldetailIDNumPlanID SSN11001111111111110012222222222100122222222221001333333333Required RESULT required(Missing employees from payroll)IDNumSSN13333333332111111111
View 1 Replies
View Related
Jun 15, 2007
Hell Sir,
I am using repeater control to show the result after search .and using checkbox control in itemtemplate row .After searchresult i am facing a problem in identifying the checked checkboxes in the itemtemplate of repeater control .
Please provide appropriate solution ....
thanks for ur attention...
View 3 Replies
View Related
May 14, 2008
Hi,
I'm coming from a language called Progress and need some basic help with SQL and ASP.net
Here's my item table from database with 6 recordscolor fruit
red applered bananared cherryblue appleblue bananablue cherry
My goal is to put in HTML tables like so..
red
apple
banana
cherry
blue
apple
banana
cherry
I was going to use the ASP.net Repeater control by doing with some SQL statement that will produce this 6 records with a calculated field..
color fruit firstColorInFruitGroupred apple yesred banana nored cherry noblue apple yesblue banana noblue cherry no
So basically when I see a yes thats when I know its a <TH>"heading"
When I see a no, thats when I see that its a <TD> "data"
How would I write this SQL statement? or is there a better way of doing this? Thanks much!
View 7 Replies
View Related
Jun 4, 2008
I need to set a Repeater.Datasource to one of three stored procedures depending on what button the user selects. How do I set it up please?<asp:SqlDataSource ID="SqlDataSource5" runat="server" ConnectionString="<%$ ConnectionStrings:ABCConnectionString %>"SelectCommand="???????????????" SelectCommandType="StoredProcedure"><SelectParameters><asp:ControlParameter ControlID="???????????????????" Name="?????????????" PropertyName="Text" Type="string" /></SelectParameters></asp:SqlDataSource>
protected void btnKeyWordSearch_Click(object sender, ImageClickEventArgs e){ mode = 1; StoredProcdureName = "KWSearch"; KWords = tbxKWordText.Text;}protected void btnCompanyNameSearch_Click(object sender, ImageClickEventArgs e){ mode = 1; StoredProcdureName = "NAMESearch"; CoName = tbxCoNameText.Text;}protected void btnBrandNameSearch_Click(object sender, ImageClickEventArgs e){ mode = 1; StoredProcdureName = "BRANDSearch"; Brand = tbxBrandText.Text;}
View 1 Replies
View Related
Feb 15, 2005
I want to build some paging functionality into my repeater (b4 you ask, datagrid not providing flexibility required for presentation).
I will have no problem with the VB logic but I will need to execute SQL that only returns results from x to y (e.g. results 21 thru 40 for page 2). I know I can do something like 'SELECT TOP 20 * FROM...', or something like it, for page 1. But, I'm not sure if it's possible to build SQL for the pages greater than 1. Any suggestions.
Thanks
Martin
View 1 Replies
View Related
Aug 29, 2005
Q1 - I want to compare file names uploaded by users with the name of the file present in the database. I have a repeated control that shows the data alongwith an array of <input type=file> that is createddynamically when the data is displayed in the repeater control. (So there is an input tag within the ItemTEmplate tag in the repeater)Now I want to compare the names of the files uploaded by the user with the values as displayed in the repeater. Is there a way I can do this? So I need to be able to get the data (for example Name) as displayed in the repeater control into a variable like Dim strName As String. Something like: Dim strName As String = (value from the repeater control) Can I do this? How?
Q2 - I want to return a value from a stored procedure that will be stored in a variable in VB and will be used for comparison. So, I want to return a 0 or 1 and then use .ReturnValue method to store this value. The problem that I am facing is that I am using a cursor. And as soon as return is called in the SP it exitsthe procedure and returns only one value (1 if found 0 otherwise) So it does not loop through the completecursor. What can I do to fix this? CODE:
OPEN cur1--print 'Cursor Open'FETCH NEXT FROM cur1 INTO @varFile, @varFileEx, @varFileSt
WHILE @@FETCH_STATUS = 0BEGINIF (@varFile = @FileName AND @varFileEx = @FileExt)BEGINset @varReturn = 0ENDELSE BEGINset @varReturn = 1ENDFETCH NEXT FROM cur_FileSystem INTO @varFileName, @varFileExt, @varFileStatusreturn (@varReturn)ENDCLOSE cur_FileSystemDEALLOCATE cur_FileSystem
Please help. Thanks
View 2 Replies
View Related
Jan 15, 2006
Hi,
I have a repeater which i need to build editing capabilities into in a similar way as the GridView, just a little unsure how to tie it together. Ideally i would like to use a GridView as this would do all of the work for me however it looks like I need to go with the repeater due to the nested nature of the data I am working with.
What is the best way to go about updating the data source from within a repeater? I have already built the edit interface with some MultiViews in the Repeater control and handling the ItemCommand event, just not sure how to actually update the data source.
Can I still use the SqlDataSource wizard to generate all of the SQL for me? If so, within the ItemCommand event handler I have the data i want to update back to the database by using the FindControl method and retrieving the Text, but how do i get this data into the SqlDataSource object and update the database?
Are there any samples available which show how to update a datasource using a repeater?
Your help is much appreciated
trenyboy
View 6 Replies
View Related
Nov 1, 2005
Hi,I'm probably missing something obvious (either that or doing this totally wrong).I'm trying to use a nested loop to generate the following results:Unit Day1 Day2 Day3 Day4 Day5Name1 25 45 89 54 76Name2 48 54 81 74 98What I have so far is this:WHILE @FCount < @TotalFoodUnitsBEGINSELECT (SELECT Unit FROM tbl_acc_FoodVenues WHERE UnitID = (@FCount + 1)) AS Unit WHILE @FDCount < @Days BEGIN SELECT (SELECT FdRevenue_a FROM tbl_acc_aud_SportsAudits WHERE AudDate = DATEADD(day, @FDCount, @pdStartDate)) AS Rev SET @FDCount = @FDCount + 1 END SET @FCount = @FCount + 1ENDAny suggestions please
View 3 Replies
View Related
Nov 15, 2001
I am trying to write a query that does not use inner joins to see if it returns rows faster than a query using inner joins.
My trouble is that I don't know how to write the syntax for the 3rd table that I am comparing against.
Can I nest Exists in a Where clause?
If so how is the 2nd exists statement added to the query?
see my sample query below
================================================== ===
'With 2 tables
SELECT DISTINCT s1.ID, s1.SITE
FROM SITE_TBL s1
WHERE EXISTS (SELECT *
FROM DEVICE_TBL d1
WHERE s1.ID = d1.SITE_ID AND d1.DELETEFLAG <> 'D')
ORDER BY SITE
'with 3 tables this doesn't work
SELECT DISTINCT s1.ID, s1.SITE
FROM SITE_TBL s1
WHERE EXISTS (SELECT *
FROM DEVICE_TBL d1
WHERE s1.ID = d1.SITE_ID AND d1.DELETEFLAG <> 'D')
AND
(SELECT *
FROM BIG_TBL b1
WHERE d1.fqdn = b1.xyz)
ORDER BY SITE
================================================== ===
Thanks for the help
Jim
View 1 Replies
View Related
Aug 4, 2001
Hi, I have the following scenario that I am not sure how to best tackle. Any
advice or examples is appreciated.
I am creating a stored proc that requires a code to be passed to it. In
return data gathered from 3 different tables will be returned. The big catch
is that 1 of the tables resided in a differenct database.
So, here is the data layout.
Database 1, Table 1 contains the following fields: Job, CustID, ShipID, and
ShipMethod.
Database 2, Table 1 contains CustID, ShipID, Address, City, State, Zip,
etc...
Database 2, Table 2 contains CustID, CustomerName.
So the first question is how should the stored proc look with an input
parameter of "Job" and output of Job, CustID, ShipMethod, ShipID, Address,
City, State, Zip, and CustomerName?
Secondly, which database should the stored proc reside?
Again, any advise, suggestions, pointers, etc. are appreciated.
View 1 Replies
View Related
Jan 26, 2006
Hi All,
Can anybody please tell me if a query such as this (Valid in MS Access)
can work in SQL Server:
SELECT Description, Sum(Total) FROM (
SELECT Description, Total FROM Table_A
UNION ALL
SELECT Description, Total FROM Table_B
UNION ALL
SELECT Description, Total FROM Table_C
)
GROUP BY Description
The group of unions work by themselves, but when I try to nest an outer query to do some a Summation(), I have syntax errors.
Any insight would be greatly appreciated. Thank you.
View 2 Replies
View Related
Feb 17, 2004
Folks
I have two queries
Select Account_Id , Branch_Cd from Accounts
SELECT SUM (dbo.HOLDING.Shares_Par_Value_Qty * dbo.ASSET.Current_Prc) AS MarketValue
FROM dbo.HOLDING INNER JOIN
dbo.ASSET ON dbo.HOLDING.Property_Num = dbo.ASSET.Property_Num
Group by dbo.HOLDING.Account_ID
Account_ID is the same in both the queries ie in both the tables
Holding and Account.
I need the output like this
Select Account_Id, Branch_Cd, MarketValue from -------
But MarketValue should be calculated exactly in the above method.
How do I combine these two queries. I need it asap.
Help me out.
Thanks
View 2 Replies
View Related
Feb 8, 2007
I have a database that contains a PERSONNEL table, a VISIT table, and a STARSHIP table.
I am trying to generate a single column list of the personnel that are from Vulcan (PERSONNEL.PLANET) and all starships that have visited Vulcan (VISIT.PLANET). VISIT.SHIP and STARSHIP.REGISTRY columns contain the ships identifiers. How would I accomplish this? I am just beginning sql so please be nice ;)
View 1 Replies
View Related
Nov 7, 2007
I have the following result set #1 from the query below. As you can see, there are four different provider roles and four different physicians listed for the same case (acctnum). Is there a way I could add a nested select (or other method) which would allow me to list this case as one line item to appear in the manner of result set #2?
RESULT SET #1 (the results of the query I have now)
MRN
ACCTNUM
PTNAME
AGE
ADMDT
DISCHDT
LOS
PROVIDER_CODE
PROVIDER_ROLE
PHYSNAME
12345
11111117777
DOE, JANE
48
Nov 29 2006
Nov 30 2006
1
10
ANE1
MILLER DR.
12345
11111117777
DOE, JANE
48
Nov 29 2006
Nov 30 2006
1
20
ADM
MAY DR.
12345
11111117777
DOE, JANE
48
Nov 29 2006
Nov 30 2006
1
30
ATT
SCHULTZ DR.
12345
11111117777
DOE, JANE
48
Nov 29 2006
Nov 30 2006
1
35
PRIN
THOMAS DR.
RESULT SET #2 (this is how I desire the results to look)
MRN
ACCTNUM
PTNAME
AGE
ADMDT
DISCHDT
LOS
ANE1PHYS
ADMPHYS
ATTPHYS
PRINPHYS
12345
11111117777
DOE, JANE
48
Dec 13 2006
Dec 14 2006
1
MILLER DR.
MAY DR.
SCHULTZ DR.
THOMAS DR.
Select
e.medrec_no,
e.account_number,
Isnull(ltrim(rtrim(pt.patient_lname)) + ', ' ,'')
+
Isnull(ltrim(rtrim(pt.patient_fname)) + ' ' ,'')
+
Isnull(ltrim(rtrim(pt.patient_mname)) + ' ','')
+
Isnull(ltrim(rtrim(pt.patient_sname)), '')
AS SRM_PatientName,
pm.PatientAge,
left(e.admission_date,11) as Admit_Date,
left(e.episode_date,11) as Disch_Date,
(CASE WHEN DATEDIFF(DAY, e.admission_date,e.episode_date) = 0 Then 1
ELSE DATEDIFF(DAY, e.admission_date,e.episode_date) END) AS LOS,
epi.PROVIDER_CODE,
epi.PROVIDER_ROLE,
pe.PERSON_NAME as physician_name,
From srm.episodes e inner join
dbo.PtMstr pm on pm.accountnumber=e.account_number inner join
srm.ITEM_HEADER ih ON ih.ITEM_KEY = e.EPISODE_KEY INNER JOIN
srm.PATIENTS pt ON pt.PATIENT_KEY = ih.LOGICAL_PARENT_KEY inner join
srm.CDMAB_PROV_EPI epi on epi.episode_key=e.episode_key inner join
srm.providers p on p.provider_key = epi.provider_key inner join
srm.person_element pe on pe.item_key = p.provider_key
Where e.episode_date is not null and pm.AnyProc like '%4495%'
View 7 Replies
View Related
Mar 17, 2008
I guess I need help in understanding how to do the nested query option and see what works here and what doesn't.
Lets go with some psudo code
SELECT Col1, Col2, COUNT(*) AS Expr1 FROM Table1 INNER JOIN Table2 ON Table1.Col2 = Table2.Col1
Why doesn't the following work, is there a work around?
SELECT Col1, Col2, COUNT(*) AS Expr1, (SELECT COUNT(*) FROM Table2) As Expr2 FROM Table1 INNER JOIN Table2 ON Table1.Col2 = Table2.Col1
View 6 Replies
View Related
Dec 6, 2006
Compilation Error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
original source code
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DatabaseConnectionString %>" SelectCommand="SELECT [authorID], [firstname] FROM [author] where id=1" ></asp:SqlDataSource>
<asp:Repeater ID="rpt" DataSourceID="SqlDataSource1" runat="server">
<ItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Style="z-index: 100; left: 65px; position: absolute;
top: 59px" Text='<%# authorID %>' ></asp:TextBox>
<asp:TextBox ID="TextBox2" runat="server" Style="z-index: 101; left: 66px; position: absolute;
top: 96px" Text='<%# firstName %>'></asp:TextBox>
</ItemTemplate>
</asp:Repeater>
<asp:Button ID="Button1" runat="server" Style="z-index: 102; left: 46px; position: absolute;
top: 164px" Text="next" />
<asp:Button ID="Button2" runat="server" Style="z-index: 103; left: 102px; position: absolute;
top: 163px" Text="first" />
<asp:Button ID="Button3" runat="server" Style="z-index: 104; left: 156px; position: absolute;
top: 162px" Text="prev" />
<asp:Button ID="Button4" runat="server" Style="z-index: 106; left: 208px; position: absolute;
top: 162px" Text="last" />
</div>
</form>
Compiler Error Message: CS0103: The name 'authorID' does not exist in the current contextSource Error:
Line 13: <asp:Repeater ID="rpt" DataSourceID="SqlDataSource1" runat="server">
Line 14: <ItemTemplate>
Line 15: <asp:TextBox ID="TextBox1" runat="server" Style="z-index: 100; left: 65px; position: absolute;
Line 16: top: 59px" Text='<%# authorID %>' ></asp:TextBox>
Line 17: <asp:TextBox ID="TextBox2" runat="server" Style="z-index: 101; left: 66px; position: absolute;
View 1 Replies
View Related
Aug 14, 2007
How to configure sqldatadapter with query like
"select name ,id from tlb1 where id in (select id from tlb2 where dept=@dept)"
Is the nested subquery is not allowed while configuring sqldaadapter?
Swati
View 1 Replies
View Related
Jun 6, 2004
Use Pubs
SELECT pub_id, type, SUM(price) as Total_price
FROM titles
GROUP BY pub_id, type
The above query returns the following resultset:
0736business 2.9900
1389business 51.9300
0877mod_cook 22.9800
1389popular_comp42.9500
0736psychology 45.9300
0877psychology 21.5900
0877trad_cook 47.8900
0877UNDECIDED NULL
Now I want to add another "Group By" on type, so I tried:
Select type, sum(Total_Price) from
(SELECT pub_id, type, SUM(price) as Total_Price
FROM titles
GROUP BY pub_id, type)
Group By type
But I got error: Incorrect syntax near the keyword 'Group'. How can I write such a nested group by query.
Thanks in advance for any help.
View 5 Replies
View Related
Jan 12, 2015
I need to know how many widgets are located at each factory.
I have a table called "Widgets". The pertinent column(s) are:
Factory UID
By using only this table I can group the results by the FactoryUID to get the answer. However, this table does not tell me the factory name.
I have a table called "Factories". The pertinent column(s) are:
FactoryUID
FactoryName
I can join these two tables by the FactoryUID. But I don't know how to write this query so that my results will look like the following table:
FactoryName Widgets
Factory1 100
Factory2 200
Factory3 300
View 6 Replies
View Related
May 25, 2007
Dear All,
I need to create a query to list all the subfolders within a folder.
I have a database table that lists the usual properties of each of the folder.
I have another database table that has two columns
1. Parent folder
2. Child folder
But this table maintains the parent child relationship only to one level.
For example if i have a folder X that has a subfolder Y and Z.
And Y has subfolders A and B.
and B has subfolder C and D
and C has subfolder E and F
The database table will look like
parentfolder child folder
X Y
X Z
Y A
Y B
B C
B D
C E
C F
I want to write a query which will take a folder name as the input and will provide me a list of all the folders and subfolders under it. The query should be based on the table (parent - child) and there should not be any restriction on the subfolder levels to search and report for.
I have been banging my head to do this but i have failed so far. Any help on this will be highly appreciated.
View 3 Replies
View Related
May 12, 2008
I'd appreciate some help with the issue below - my SQL is a bit rusty and was never that hot to be frank. I'm using SQL Server 2000 (although have a test box with 2005 Express also). I've trawled MSDN and a few forums but can't find the solution (maybe I don't know what I'mm looking for!), so any help would be marvellous...
I have a table with a field called 'IRV' containing a string of comma-separated values. I want to be able to query a point in that string and count the number of times a given value appears. So...as an example, I want to count how many times '1' appears at position 7 in the IRV. I can create SQL to do this as follows:
SELECT COUNT(X) AS is1
FROM myIRVtable
WHERE (SUBSTRING(IRV, 7, 1) = '1')
So far so good. However, it is also possible that the value at position 7 in this string could be '2' (or '3', or '4', etc) - and rather than re-running the query again and again to get these values, I'd like to do it in one hit.
How can I combine all this together - anyone have any brilliant solutions?
View 4 Replies
View Related
Jan 31, 2008
I'm having a trouble with a nested scalar query
I have a table that refers to itself, and I need to loop through it to get the total number of entries in the structure with an object_type of 40 this is the function I came up with to do this. The problem is that the nested function doesn't seem to get called.
Code Snippet
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Collections.Generic;
using Microsoft.SqlServer.Server;
public partial class StoredProcedures
{
private struct PerformanceCriteriaCounter
{
public PerformanceCriteriaCounter(int id, string objecttype)
{
Id = id;
Object_Type = objecttype;
}
public int Id;
public string Object_Type;
}
[Microsoft.SqlServer.Server.SqlProcedure(Name = "usp_PerformanceCriteriaCounter")]
public static int CountPerformanceCriteria(int ParentID, int SourcePosition)
{
using (SqlConnection conn = new SqlConnection("context connection=true"))
{
int Counter = 0;
int Counter2 = 0;
SqlContext.Pipe.Send("Called with ParentID=" + ParentID + " SourcePosition=" + SourcePosition);
conn.Open();
using (SqlCommand myCommand = conn.CreateCommand())
{
myCommand.CommandText = @"SELECT CompetenceLearningObject.Object_Type, CompetenceLearningObject.LearningObject_ID
FROM CompetenceLearningObjectParent INNER JOIN
CompetenceLearningObject ON CompetenceLearningObjectParent.LearningObject_ID = CompetenceLearningObject.LearningObject_ID
WHERE (CompetenceLearningObjectParent.Approved = 1) AND (CompetenceLearningObject.Archived = 0 OR
CompetenceLearningObject.Archived IS NULL) AND (CompetenceLearningObject.Approved_Status = 1) AND
(CompetenceLearningObjectParent.Parent_ID = @ParentID) AND (CompetenceLearningObjectParent.Position_ID = @SourcePosition)";
myCommand.Parameters.AddWithValue("@ParentID", ParentID);
myCommand.Parameters.AddWithValue("@SourcePosition", SourcePosition);
List<PerformanceCriteriaCounter> loList = new List<PerformanceCriteriaCounter>();
SqlDataReader reader = myCommand.ExecuteReader();
while (reader.Read())
{
SqlContext.Pipe.Send("Adding item");
loList.Add(new PerformanceCriteriaCounter(int.Parse(reader["LearningObject_ID"].ToString()), reader["Object_Type"].ToString()));
}
reader.Close();
foreach (PerformanceCriteriaCounter lo in loList)
{
SqlContext.Pipe.Send("Testing item, ObjectType =" + lo.Object_Type);
if (lo.Object_Type == "40")
{
SqlContext.Pipe.Send("Incrementing counter");
Counter++;
}
else
{
SqlContext.Pipe.Send("Calling procedure with ParentID=" + lo.Id + " and Position=" + SourcePosition);
using (SqlCommand myCommand3 = conn.CreateCommand())
{
myCommand3.CommandType = CommandType.StoredProcedure;
myCommand3.CommandText = "usp_PerformanceCriteriaCounter";
myCommand3.Parameters.AddWithValue("@ParentID", lo.Id);
myCommand3.Parameters.AddWithValue("@SourcePosition", SourcePosition);
object objValue = myCommand3.ExecuteScalar();
if (objValue != DBNull.Value)
{
Counter2 = Convert.ToInt32(objValue);
SqlContext.Pipe.Send("It's not null value=" + Counter2.ToString());
Counter = Counter + Counter2;
}
}
}
}
}
return Counter;
}
}
}
This is the output from SQL Server when I call the function.
Code Snippet
Called with ParentID=1 SourcePosition=89
Adding item
Adding item
Adding item
Adding item
Adding item
Adding item
Adding item
Adding item
Adding item
Adding item
Adding item
Adding item
Adding item
Testing item, ObjectType =30
Calling procedure with ParentID=2 and Position=89
It's not null value=0
Testing item, ObjectType =30
Calling procedure with ParentID=3 and Position=89
It's not null value=0
Testing item, ObjectType =30
Calling procedure with ParentID=4 and Position=89
It's not null value=0
Testing item, ObjectType =30
Calling procedure with ParentID=5 and Position=89
It's not null value=0
Testing item, ObjectType =30
Calling procedure with ParentID=6 and Position=89
It's not null value=0
Testing item, ObjectType =30
Calling procedure with ParentID=7 and Position=89
It's not null value=0
Testing item, ObjectType =30
Calling procedure with ParentID=8 and Position=89
It's not null value=0
Testing item, ObjectType =20
Calling procedure with ParentID=9 and Position=89
It's not null value=0
Testing item, ObjectType =20
Calling procedure with ParentID=10 and Position=89
It's not null value=0
Testing item, ObjectType =20
Calling procedure with ParentID=11 and Position=89
It's not null value=0
Testing item, ObjectType =20
Calling procedure with ParentID=12 and Position=89
It's not null value=0
Testing item, ObjectType =20
Calling procedure with ParentID=13 and Position=89
It's not null value=0
Testing item, ObjectType =20
Calling procedure with ParentID=14 and Position=89
It's not null value=0
You can see it adding and checking the values and attempting to call itself, but it never seems to get re-called, any ideas?
Cheers
Jon
View 3 Replies
View Related
Sep 11, 2007
Hi,
I am trying to limit a result set by ROW_NUMBER. However, I am having problems getting it working.
The following query works fine, and I get a result set with PollID, AddedDate and RowNum columns.
SELECT *, ROW_NUMBER() OVER (ORDER BY Results.AddedDate DESC) AS RowNum FROM
( SELECT DISTINCT p.PollID, p.AddedDate
FROM vw_vs_PollsWithVoteCount p
JOIN vs_PollOptions o ON p.PollID = o.PollID
) AS Results
However, as soon as I add a WHERE condition:
SELECT *, ROW_NUMBER() OVER (ORDER BY Results.AddedDate DESC) AS RowNum FROM
( SELECT DISTINCT p.PollID, p.AddedDate
FROM vw_vs_PollsWithVoteCount p
JOIN vs_PollOptions o ON p.PollID = o.PollID
) AS Results
WHERE RowNum BETWEEN 1 AND 10
The query fails with an ' Invalid column name 'RowNum' ' error.
I have tried using 'Results.RowNum' but I get the same problem.
I don't understand what the issue is. The result set has a column headed 'RowNum' so why can't I apply a WHERE clause to this column? I can apply WHERE to the PollID column, for example, with no problem.
Any help very much appreciated.
Thanks...
View 7 Replies
View Related
Jan 27, 2008
I'm about ready to pull my hair out. I have a repeater control, and a date field. If the field is a valid date, I'll use it to calculate and display the person's age. Otherwise, I want to display "N/A". My problem is trying to determine if the date field is null or not.I'm using SQL Server 2005 which allows Nulls in the date field, and for many records I don't have a birth date. It makes sense for these records to leave the date Null. This is my code:Protected Sub Repeater1_ItemDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.RepeaterItemEventArgs) Handles Repeater1.ItemDataBound If e.Item.ItemType = ListItemType.Item OrElse e.Item.ItemType = ListItemType.AlternatingItem Then Dim LabelIcon As Label = CType(e.Item.FindControl("LabelIcon"), Label) Dim LblAge As Label = CType(e.Item.FindControl("LblAge"), Label) Dim inmate As WAP.prisonmembersRow = CType(CType(e.Item.DataItem, System.Data.DataRowView).Row, WAP.prisonmembersRow) If System.IO.File.Exists(Server.MapPath("~/images/picts/" & inmate.FILE2 & ".jpg")) Then LabelIcon.Visible = True End If If inmate.DATE_OF_BIRTH Is DBNull.Value Then If IsDate(inmate.DATE_OF_BIRTH) Then LblAge.Text = "Age: N/A" Else LblAge.Text = "Age: " & GetBirthdate(inmate.DATE_OF_BIRTH) End If End If End IfEnd Sub How can I resolve this?Diane
View 7 Replies
View Related
Oct 8, 2012
I have added some SQL to an Access form which updates the dbo_BM_Map table when the user hits the Apply button. There is a temp table with various fields, two being "Chapter_No" and "Initial_Mapping_Complete" which the update is based on.
I want this update to only apply to chapters that only have one name in the "Initial_Mapping_Complete" column. If a chapter has more than one then the update should ignore it. The attached screengrab shows you. The update should ignore chapter 19 as there are two people (Jim and James) in the Initial_Mapping_Complete field. Here is my code.
pdate dbo_BM_Map inner Join Temp_Progression_Populate
on dbo_BM_Map.Product_ID = Temp_Progression_Populate.Product_ID
Set dbo_BM_Map.Initial_Mapping_Complete = Temp_Progression_Populate.Initial_Mapping_Complete
Where dbo_BM_Map.Chapter_No = Temp_Progression_Populate.Chapter_No
And Temp_Progression_Populate.Initial_Mapping_Complete in
(Select count(Initial_Mapping_Complete), Chapter_No
from Temp_Progression_Populate
Group by Chapter_No
Having Count(Initial_Mapping_Complete) = 1)
View 2 Replies
View Related