Request ID Parent ID Account Name Addresss 1452 1254789 Wendy's Atlanta Georgia 1453 1254789 Wendy's Norcross Georgia 1456 1254789 Waffle House Atlanta Georgia
............child |parent|.............a1 |a | .............a2 |a |.............a11 |a1 |.............b1 |b |.............b11 |b1 |.............b111 |b1 |............. Here is my table I want to get all childs of "a" ie {a1,a11,a2}I mean recursivelyie child,chid of child ,child of child of child ........etc up to any extentet the table containHow can i for mulate the select querry?
1. to display all parent with ORDER BY ItemOrder (no need to sort by ItemDate) 2. display all child row right after their parent (ORDER BY ItemOrder if ItemDate are same, else ORDER BY ItemDate) 3. display all grand child row right after their parent (ORDER BY ItemOrder if ItemDate are same, else ORDER BY ItemDate)
I have table "Clients" who have associated records in table "Mailings" I want to populate a gridview using a single query that grabs all the info I need so that I may utilize the gridview's built in sorting. I'm trying to return records containing the next upcoming mailing for each client.
The closest I can get is below: I'm using GROUP BY because it allows me to return a single record for each client and the MIN part allows me to return the associated record in the mailings table for each client that contains the next upcoming 'send_date'
SELECT MIN(dbo.tbl_clients.client_last_name) AS exp_last_name, MIN(dbo.tbl_mailings.send_date) AS exp_send_date, MIN(dbo.tbl_mailings.user_id) AS exp_user_id, dbo.tbl_clients.client_id, MIN(dbo.tbl_mailings.mailing_id) AS exp_mailing_idFROM dbo.tbl_clients INNER JOIN dbo.tbl_mailings ON dbo.tbl_clients.client_id = dbo.tbl_mailings.client_idWHERE (dbo.tbl_mailings.user_id = 1000)GROUP BY dbo.tbl_clients.client_id The user_id set at 1000 part is what makes it rightly pull in all clients for a particular user. Problem is, by using the GROUP BY statement I'm just getting the lowest 'mailing_id' number and NOT the actual entry associated with mailing item I want to return. Same goes for the last_name field. Perhaps I need to have a subquery within my WHERE clause?Or am I barking up the wrong tree entirely..
I was playing around with the new SQL 2005 CLR functionality andremembered this discussion that I had with Erland Sommarskog concerningperformance of scalar UDFs some time ago (See "Calling sp_oa* infunction" in this newsgroup). In that discussion, Erland made thefollowing comment about UDFs in SQL 2005:[color=blue][color=green]>>The good news is that in SQL 2005, Microsoft has addressed several of[/color][/color]these issues, and the cost of a UDF is not as severe there. In fact fora complex expression, a UDF in written a CLR language may be fasterthanthe corresponding expression using built-in T-SQL functions.<<I thought the I would put this to the test using some of the same SQLas before, but adding a simple scalar CLR UDF into the mix. The testinvolved querying a simple table with about 300,000 rows. Thescenarios are as follows:(A) Use a simple CASE function to calculate a column(B) Use a simple CASE function to calculate a column and as a criterionin the WHERE clause(C) Use a scalar UDF to calculate a column(D) Use a scalar UDF to calculate a column and as a criterion in theWHERE clause(E) Use a scalar CLR UDF to calculate a column(F) Use a scalar CLR UDF to calculate a column and as a criterion inthe WHERE clauseA sample of the results is as follows (time in milliseconds):(295310 row(s) affected)A: 1563(150003 row(s) affected)B: 906(295310 row(s) affected)C: 2703(150003 row(s) affected)D: 2533(295310 row(s) affected)E: 2060(150003 row(s) affected)F: 2190The scalar CLR UDF function was significantly faster than the classicscalar UDF, even for this very simple function. Perhaps a more complexfunction would have shown even a greater difference. Based on this, Imust conclude that Erland was right. Of course, it's still faster tostick with basic built-in functions like CASE.In another test, I decided to run some queries to compare built-inaggregates vs. a couple of simple CLR aggregates as follows:(G) Calculate averages by group using the built-in AVG aggregate(H) Calculate averages by group using a CLR aggregate that similatesthe built-in AVG aggregate(I) Calculate a "trimmed" average by group (average excluding highestand lowest values) using built-in aggregates(J) Calculate a "trimmed" average by group using a CLR aggregatespecially designed for this purposeA sample of the results is as follows (time in milliseconds):(59 row(s) affected)G: 313(59 row(s) affected)H: 890(59 row(s) affected)I: 216(59 row(s) affected)J: 846It seems that the CLR aggregates came with a significant performancepenalty over the built-in aggregates. Perhaps they would pay off if Iwere attempting a very complex type of aggregation. However, at thispoint I'm going to shy away from using these unless I can't find a wayto do the calculation with standard SQL.In a way, I'm happy that basic SQL still seems to be the fastest way toget things done. With the addition of the new CLR functionality, Isuspect that MS may be giving us developers enough rope to comfortablyhang ourselves if we're not careful.Bill E.Hollywood, FL------------------------------------------------------------------------- table TestAssignment, about 300,000 rowsCREATE TABLE [dbo].[TestAssignment]([TestAssignmentID] [int] NOT NULL,[ProductID] [int] NULL,[PercentPassed] [int] NULL,CONSTRAINT [PK_TestAssignment] PRIMARY KEY CLUSTERED([TestAssignmentID] ASC)--Scalar UDF in SQLCREATE FUNCTION [dbo].[fnIsEven](@intValue int)RETURNS bitASBEGINDeclare @bitReturnValue bitIf @intValue % 2 = 0Set @bitReturnValue=1ElseSet @bitReturnValue=0RETURN @bitReturnValueEND--Scalar CLR UDF/*using System;using System.Data;using System.Data.SqlClient;using System.Data.SqlTypes;using Microsoft.SqlServer.Server;public partial class UserDefinedFunctions{[Microsoft.SqlServer.Server.SqlFunction(IsDetermini stic=true,IsPrecise=true)]public static SqlBoolean IsEven(SqlInt32 value){if(value % 2 == 0){return true;}else{return false;}}};*/--Test #1--Scenario A - Query with calculated column--SELECT TestAssignmentID,CASE WHEN TestAssignmentID % 2=0 THEN 1 ELSE 0 END ASCalcColumnFROM TestAssignment--Scenario B - Query with calculated column as criterion--SELECT TestAssignmentID,CASE WHEN TestAssignmentID % 2=0 THEN 1 ELSE 0 END ASCalcColumnFROM TestAssignmentWHERE CASE WHEN TestAssignmentID % 2=0 THEN 1 ELSE 0 END=1--Scenario C - Query using scalar UDF--SELECT TestAssignmentID,dbo.fnIsEven(TestAssignmentID) AS CalcColumnFROM TestAssignment--Scenario D - Query using scalar UDF as crierion--SELECT TestAssignmentID,dbo.fnIsEven(TestAssignmentID) AS CalcColumnFROM TestAssignmentWHERE dbo.fnIsEven(TestAssignmentID)=1--Scenario E - Query using CLR scalar UDF--SELECT TestAssignmentID,dbo.fnIsEven_CLR(TestAssignmentID) AS CalcColumnFROM TestAssignment--Scenario F - Query using CLR scalar UDF as crierion--SELECT TestAssignmentID,dbo.fnIsEven_CLR(TestAssignmentID) AS CalcColumnFROM TestAssignmentWHERE dbo.fnIsEven(TestAssignmentID)=1--CLR Aggregate functions/*using System;using System.Data;using System.Data.SqlClient;using System.Data.SqlTypes;using Microsoft.SqlServer.Server;[Serializable][Microsoft.SqlServer.Server.SqlUserDefinedAggregate (Format.Native)]public struct Avg{public void Init(){this.numValues = 0;this.totalValue = 0;}public void Accumulate(SqlDouble Value){if (!Value.IsNull){this.numValues++;this.totalValue += Value;}}public void Merge(Avg Group){if (Group.numValues > 0){this.numValues += Group.numValues;this.totalValue += Group.totalValue;}}public SqlDouble Terminate(){if (numValues == 0){return SqlDouble.Null;}else{return (this.totalValue / this.numValues);}}// private accumulatorsprivate int numValues;private SqlDouble totalValue;}[Serializable][Microsoft.SqlServer.Server.SqlUserDefinedAggregate (Format.Native)]public struct TrimmedAvg{public void Init(){this.numValues = 0;this.totalValue = 0;this.minValue = SqlDouble.MaxValue;this.maxValue = SqlDouble.MinValue;}public void Accumulate(SqlDouble Value){if (!Value.IsNull){this.numValues++;this.totalValue += Value;if (Value < this.minValue)this.minValue = Value;if (Value > this.maxValue)this.maxValue = Value;}}public void Merge(TrimmedAvg Group){if (Group.numValues > 0){this.numValues += Group.numValues;this.totalValue += Group.totalValue;if (Group.minValue < this.minValue)this.minValue = Group.minValue;if (Group.maxValue > this.maxValue)this.maxValue = Group.maxValue;}}public SqlDouble Terminate(){if (this.numValues < 3)return SqlDouble.Null;else{this.numValues -= 2;this.totalValue -= this.minValue;this.totalValue -= this.maxValue;return (this.totalValue / this.numValues);}}// private accumulatorsprivate int numValues;private SqlDouble totalValue;private SqlDouble minValue;private SqlDouble maxValue;}*/--Test #2--Scenario G - Average Query using built-in aggregate--SELECT ProductID, Avg(Cast(PercentPassed AS float))FROM TestAssignmentGROUP BY ProductIDORDER BY ProductID--Scenario H - Average Query using CLR aggregate--SELECT ProductID, dbo.Avg_CLR(Cast(PercentPassed AS float)) AS AverageFROM TestAssignmentGROUP BY ProductIDORDER BY ProductID--Scenario I - Trimmed Average Query using built in aggregates/setoperations--SELECT A.ProductID,CaseWhen B.CountValues<3 Then NullElse Cast(A.Total-B.MaxValue-B.MinValue ASfloat)/Cast(B.CountValues-2 As float)End AS AverageFROM(SELECT ProductID, Sum(PercentPassed) AS TotalFROM TestAssignmentGROUP BY ProductID) ALEFT JOIN(SELECT ProductID,Max(PercentPassed) AS MaxValue,Min(PercentPassed) AS MinValue,Count(*) AS CountValuesFROM TestAssignmentWHERE PercentPassed Is Not NullGROUP BY ProductID) BON A.ProductID=B.ProductIDORDER BY A.ProductID--Scenario J - Trimmed Average Query using CLR aggregate--SELECT ProductID, dbo.TrimmedAvg_CLR(Cast(PercentPassed AS real)) ASAverageFROM TestAssignmentGROUP BY ProductIDORDER BY ProductID
Given the sample data and query below, I would like to know if it is possible to have the outcome be a single row, with the ChildTypeId, c.StartDate, c.EndDate being contained in the parent row. So, the outcome I'm hoping for based on the data below for ParentId = 1 would be:
1 2015-01-01 2015-12-31 AA 2015-01-01 2015-03-31 BB 2016-01-01 2016-03-31 CC 2017-01-01 2017-03-31 DD 2017-01-01 2017-03-31
declare @parent table (Id int not null primary key, StartDate date, EndDate date) declare @child table (Id int not null primary key, ParentId int not null, ChildTypeId char(2) not null, StartDate date, EndDate date) insert @parent select 1, '1/1/2015', '12/31/2015' insert @child select 1, 1, 'AA', '1/1/2015', '3/31/2015'
Guys I need help with sql server 2005 syntax My goal is up update a table called UserStats. I have numerous functions in SQL that return Scalars (one for each statistics I want to use) How do I then use a stored proceedure to return a table of the values for use on my site?
WIthin SQL Server 2005, there are functions. This feature is new to me and I haven't found anyone that has written their own fucntions? I'm wondering if functions are written the same as stored procedures, and can a function be called from a stored procedure or even from within a query.
hello Im having a difficult time translating this query from Access to SQL because it uses the First/Last functions.
I have a 'Projects' Table and a 'Project_Comments' table, each has a 'Project_ID' field which links the 2 together. What I need to do is retrieve a Project List from the Projects Table and also the first Comment of each project based on the Commend_date field in the Project_Comments table. This is the MS ACCESS query:
SELECT Projects.Project_Number, Projects.Project_Name, First(Project Comments.Comment_Date), First(Project_Comments.Notes) FROM Projects Left Join Projec_Comments ON Projects.Project_Number = Project_Comments.Project_Number GROUP BY Projects.Project_Number, Projects.Project_Name
Now I can use Min() for the Date instead of First, however I dont know what to do with the Notes field. Any help on how to get this over to sql would be greatly appreciated!
I have created a function that returns a comma seperated list of product id's from a table. I need to call this function from a stored procedure to help filter my product results, something like the following:
SET @SQL = 'SELECT dbo.Products.ProductID FROM dbo.Products WHERE dbo.Products.ProductID IN (' + dbo.GetModels('dbo.Products.ProductID', '') + '))'
The problem I am having when executing the above is:
"Conversion failed when converting the varchar value 'dbo.Products.ProductID' to data type int."
Can anyone shed some light on how I can call the function, feeding through the product ID from the row of the select statement I am trying to execute (if this makes sense).
Iam trying to convert a date string to date format.....in access I could just use CDate, but SQL apparently does not allow this. Any help appreciated Thanks
Hello,how I can use a function of my own within a select statement. I triedcreate function funny() returns intas beginreturn( 2 )end goand then "select funny()" but 'funny' is not a recognized function name.How can I solve this?thanks and regardsMark
Hi,,I'm having a problem with calling a function from an activex scriptwithin a data transformation. the function takes 6 inputs and returnsa single output. My problem is that after trying all of the stuff onBOL I still can't get it to work. It's on the same database and I'mrunning sql 2000.when I try to call it I get an error message saying "object requiredfunctionname" If I put dbo in front of it I get "object required dbo".Can anyone shed any light on how i call this function and assign theoutput value returned to a variable name.thanks.
I've created a function that performs modulo. I understand that SQL server 2000 / 2005 uses % for modulo, but we have an application that was written for Oracle. Oracle has a mod(dividend, divisor) function.
As to not rewite the queries, I would like to implement the function below:
the function executes properly but I must prefix it with the dbo schema.
Net: I can execute --- select dbo.mod(9,2) and it returns a 1 just like it should.
but I can not execute --- select mod(9,2) I receive the error "'mod' is not a recognized function name." on SQL 2000 and 2005.
If I can execute select mod(9,2) then I won't need to re-write any queries.
Also, on SQL 2005, I have tried to adjust the default shema, and the execute as clause, but neither helped my cause.
I'm going to try building the function in the CLR, but I think I will be faced with the same problem.
Can someone point me in the right direction?
Thanks
Tom
create function mod ( @dividend int, @divisor int ) RETURNS int as begin declare @mod int select @mod = @dividend % @divisor return @mod end
I have to calculate data in function with "EXEC". During runtime I get the Error:
"Only functions and extended stored procedures can be executed from within a function."
I would use a Stored Procedure, but the function is to be called from a view. I don't understand, why that should not be possible. Is there any way to shut that message down or to work around? btw: Storing all the data in a table, would mean a lot of work, I rather not like to do. ;-)
Can someone explain what the different SQL CE DLL's functions are? I can issue a successful merge replication and these seem to be the DLL's loaded just after it completes.
RSSWM.exe base address: 2C000000 ========================= sqlceoledb30.dll 00CB0000 35000 A sqlceca30.dll 00CF0000 75000 A sqlceqp30.dll 00D70000 DD000 A sqlcese30.dll 00E50000 6A000 A sqlceer30en.dll 00EC0000 24000 A itcnetreg.dll 00EF0000 15000 A itcswinsock.dll 00F10000 D000 A itc50.dll 00F30000 27000 A sqlceme30.dll 00F70000 10000 A rsshelper.dll 00F80000 6000 A tcpconnectiona.dll 00F90000 10000 A edbgtl.dll 00FA0000 14000 A itceventlog.dll 01110000 B000 A rsaenh.dll 01350000 2B000 RO, H, S, C, RAM from ROM iq_lapi_c_wrapper.dll 01B80000 27000 RO, XIP ssapi.dll 01BB0000 17000 RO, XIP mscoree2_0.dll 01D90000 C3000 RO, H, S, XIP
After some application activity, I attempt a merge replication again and it fails with a "DLL could not be loaded" yadda, yadda message. These seem to be the loaded DLL's at this point.
RSSWM.exe base address: 2C000000 ========================= sqlceqp30.dll 00D70000 DD000 A sqlcese30.dll 00E50000 6A000 A sqlceer30en.dll 00EC0000 24000 A itcnetreg.dll 00EF0000 15000 A itcswinsock.dll 00F10000 D000 A itcadcdevmgmt.dll 00F20000 9000 A itc50.dll 00F30000 27000 A sqlceme30.dll 00F70000 10000 A rsshelper.dll 00F80000 6000 A tcpconnectiona.dll 00F90000 10000 A edbgtl.dll 00FA0000 14000 A itceventlog.dll 01110000 B000 A rsaenh.dll 01350000 2B000 RO, H, S, C, RAM from ROM iq_lapi_c_wrapper.dll 01B80000 27000 RO, XIP ssapi.dll 01BB0000 17000 RO, XIP mscoree2_0.dll 01D90000 C3000 RO, H, S, XIP
I'm at a loss as to why SQL CE cannot load unless I am out of my 32MB of process space for some reason.
hi, i have two tables i want the identity value of the parent table to be inserted into the chile table here is my code,but i don't know why it isn't working ! protected void Button1_Click(object sender, EventArgs e) { string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; string pcontent = TextBox1.Text; string data = TextBox2.Text; addtopic(pcontent,connectionString); addfile(data, connectionString); } public void addtopic(string subject,string connstring) { using (SqlConnection connection = new SqlConnection(connstring)) { SqlCommand command = new SqlCommand("INSERT INTO parent" + "(content)" + "Values(@content)", connection); command.Parameters.Add("@content", SqlDbType.Text).Value = subject; connection.Open(); command.ExecuteNonQuery(); } } public void addchild(string name, string connstring) { using (SqlConnection connection = new SqlConnection(connstring)) {Guid id = Guid.NewGuid(); SqlCommand commandd = new SqlCommand("INSERT INTO child" + "(parentid,data,uniqueid)" + "Values(@@IDENTITY,@data,@uid)", connection); commandd.Parameters.Add("@data", SqlDbType.NVarChar, 50).Value = name; commandd.Parameters.Add("@uid", SqlDbType.UniqueIdentifier).Value = id;
I have a parent/child relationship in a relational database broken out like this: Table Name: categories[category_id] int (primary_key NOT NULL),[category_name] varchar(50),[parent_fk] int The parent references the category_id in the same table to create the parent/child relationships. I can get all the bottom level categories by doing this: select category_id, category, parent_fk from categories where category_id not in ( select parent_fk from categories) Each bottom-level category has a count attached to it. The problem I have is getting the counts rolled up for each parent of the bottom level. A parent could/will have multiple bottom-level categories (and counts). My sql is a little weak, could you help me out? I can utilize everying in SQL 2000 (stored proc, UDF, anything). Thanks!
Good morning, I have two tables PARENTTBL which is a parent table and CHILDTBL which is a Child table . For each insert in the Parent table i want to insert values in the child Table but (when inserting in child table) i want the Field FILED2 which is a varchar one will receive the value of the PKEY int cancatenated with a sequnetial value for each new PKEY FILED2 = Rtrim(LTreim(Str(PKEY))+ Sequential # . which is a Sequential # by PKEY value .
Exemple : If i insert 100,A,B in PARENTTBL (100 is a PK value) i want to insert in CHILDTBL the following data : 125,100-1 126,100-2 300,100-3 452,100-4 The first column is the Child PK and the second column is the FILED2 I want to do this in one insert instead of insert then Update.
I don't find the equivalent of Number(*) of SYBASE or ROWNUM of Oracle in order to do This .
I have table1 which has many unique ID numbers and table2 that has many records for each ID. some of the ID numbers in table1 have changed and I have created a translation table (table3) that links the old and new ID numbers.
What I need to do is some sort of update sql statement that updates all the records in table2 changing all the oldID numbers to the new ones using the translation table.
Table1 and table2 are not linked...can anyone help me with the sql statement
example
Table 1 IDNUM NAME 12345 Joe 12346 Mary 12347 David
Is it possible to roll up all child records into one comma delimited field? For example, if the parent table is league info, and the child table is team info, I would be looking to return results like this:
Field 1 Field 2 NFL Bears, Browns, Saints, etc NBA Bulls, Celtics, Lakers, etc
George writes "SQL server 2005 Express, Windows XP Pro SP2
I want to create a stored procedure that will insert a record in a child table (tblcontproj)propulating two columns with columns from the parent (InterestListoriginal)and two columns with user selected values. I created an insert select statement that looks like ..
" INSERT INTO tblcontproj(proj_rpt_id, proj_name) SELECT proj_rpt_id, project_name FROM InterestListoriginal WHERE (proj_rpt_id = @proj_rpt_id)"
This works great! Now can I add two columns to the INTO clause for projcontshortname and projconttye and use a VALUE clause that sets tblcontproj.projcontshortname and tblcontproj.projconttype to @projcontshortname and @projconttype which are user selected values from a downdownlist.
I want to find all the child of a node in a tree . A child can have multiple parent i.e 2 can be place under multiple parent . The folling is the data:
This structure requires complicated queries (recursive call) to find out all the child of a root node, so I have added another field for the root id. Is this a good relational database design ? kindly suggest.
In our database we have a list of devices in a "Device" Table, eachhaving one or more IP's located in the "IP" Table linked through aforein key on the DeviceID Column.I would like to retrieve this information as SuchDeviceID IpAddress1 10.0.0.1, 10.0.0.2, 10.0.0.32 ...345etc.Is it possible to do that without using cursors? Through a query?
I have a parent package which execute a child package. But when the child package is run from the parent not all of the tools inside is executed. I have a variable "ExecuteStep" from the parent that gives information about which tools, that needs to be executed.
BUT
The child package should be able to run independently also. In this case all tools inside the package should execute. This is however not possible because my variable "ExecuteStep" does not exist inside the package, it is inheritage from my parent.
If I create a variable with exactly the same name inside my child package, I can run the child independently, but when executed from the parent the value from the parent package is now overwritten by the child variable.
I am a little bit confused about Transactions, the connection string parameter "RetainSameConnection" and the execution of a child package...
I have a parent package, which should execute some child packages in a loop depending on a sql dataset. doing this using variables works fine. I am setting the variables for Source and Destination also and I am having a connection manager for source and destination in the parent package.
The child packages alos have source and destination connection managers depending on variables coming from the parent package.
I am forced to use transactions on the destination, to be able to rollback if an error occurs.
When I initiate the transaction in my parent, call the child package with its own connection manager depending on the variables coming from the parent package will it be the same Transaction in my child and will it be possible to commit the transaction?
If this is not a proper way to do it is there another way to handle this?
I searched for an answer for this, and found a few good threads, but none of them seem to be doing quite the same thing I'm trying to do.
I have two packages, parent and child. Parent does basic file manipulation -- encrypting/decrypting, moving from server to server, backing up to archive, pulling/pushing to external server via FTP, etc. It is completely dumb to what child does. Child is the guts of the data work -- the ETL package.
The goal is to have this one parent package be used by several ETL child packages. But not only can parent use different children (depending on which config is used when executing parent), but child can also handle different tasks, depending on a configuration it uses.
Let me break it down further.
Three packages:
ParentPackage - Used by all jobs ChildPackage1 - Used for processing orders ChildPackage2 - Used for processing inventory
Four configurations (thus four jobs):
Job1Configuration - Used for processing orders for ClientA Job2Configuration - Used for processing orders for ClientB Job3Configuration - Used for processing inventory for ClientA Job4Configuration - Used for processing inventory for ClientB
Job1Configuration is set up to tell ParentPackage to use ChildPackage1, and to provide ChildPackage1 w/ various data for ClientA -- and so forth.
To my understanding, there is no passthrough of the config data from parent to child. A child package doesn't "inherit" or otherwise receive the information from the parent package, unless explicit variables are set up. This won't work for us, because ParentPackage is dumb of any data that the child packages may need. In other words, we don't want to set up ParentPacakge with every possible variable that every child package may need.
Also, I'm not aware of a way of setting up a job to provide a child package directly w/ a package configuration.
Is there any way to do what I'm trying to accomplish?
If I didn't explain something clearly, let me know and I will try to clarify.