I have a multi-level folders table, named folders with attributes of folder_id, parent_id and user_id, and have another table, users, contains all the user_id. I need to list all the users for each folder which has parent_id = 0 and its all sub-folders' users into one table. I have created a function to return a table with folder_id and user_id for one single folder. However, I don't know how to use this function to get the sub-folder's users and merge them together as one single table.
Here is my function:
CREATE FUNCTION [dbo].[FolderUsers] (@fid int)
RETURNS Table AS
Return
(select folder_id, f.user_id
from folders f, users u
where f.user_id = u.user_id and folder_id = @fid)
Go
where @fid is the top folder with parent_id = 0 at here, the next level sub-folder's parent_id would be = @fid.
I am thinking to have recursive call from the parent_id = @fid that returns another table and have to concatenate to the called table. I have been thinking of store procedure, "insert into" and so on, but don't know how to implement it.
Do you have any good inspiration for me? Thank you in advance!
I started with an inline table returning function with a hard coded input table name. This works fine, but my boss wants me to generalize the function, to give it in input table parameter. That's where I'm running into problems.
In one forum, someone suggested that an input parameter for a table is possible in 2012, and the example I saw used "sysname" as the parameter type. It didn't like that. I tried "table" for the parameter type. It didn't like that.
The other suggestion was to use dynamic sql, which I assume means I can no longer use an inline function.
This means switching to the multi-line function, which I will if I have to, but those are more tedious.
Any syntax for using the inline function to accomplish this, or am I stuck with multi-line?
A simple example of what I'm trying to do is below:
Create FUNCTION [CSH388102].[fnTest] ( -- Add the parameters for the function here @Source_Tbl sysname ) RETURNS TABLE AS RETURN ( select @Source_Tbl.yr from @Source_Tbl )
Error I get is:
Msg 1087, Level 16, State 1, Procedure fnTest, Line 12 Must declare the table variable "@Source_Tbl".
If I use "table" as the parameter type, it gives me:
Msg 156, Level 15, State 1, Procedure fnTest, Line 4 Incorrect syntax near the keyword 'table'. Msg 137, Level 15, State 2, Procedure fnTest, Line 12 Must declare the scalar variable "@Source_Tbl".
Hi there, Any tips on my problem would be most welcome...
right, the scenario.
A web Blog
blogger1 posts a blog_entry, e.g I love the simpsons blogger2 comments on that blog_entry, e.g No, I hate the simpsons Blogger3 comments on that comment, ie, How can you hate the simpsons.
so you can comment on a comment on a comment etc.. lool.
right, i have got two tables... Blog_entry & comment. i need to be able to search for a blog_entry + all the comments on that blog_entry..
at the moment i can search for the comments on the blog_entry using the FK in the comment table.
blog_entry INSERT INTO Blog_Entry VALUES(0001,'I love the Simpsons');
comments INSERT INTO Comment VALUES(0001,' No I hate the simpsons, cID 1000);
but i need to be able to search for the comments on comments
INSERT INTO Comment VALUES(0001,' How can you hate the simpsons, cID1000);
hopefully you can see the problem here, with only one comments table how can i get the search for the comment on the comment.. there’s nothing linking them... I could make a sub comments table, and use a FK (as with the blog_entry & first comment)
but then I would have to make another sub sub table to be able to get those comments on the first sub table... this would go on and on for each comment on comment.
you can see the cID1000 (comment PK) I can't use this to get the comment because its duplicating the PK...
So, I need to be able to search for the comments on comments… eg. I need to be able to search for blogger2, and any comments that were made on his comments.
Someone I know mention using recursion to get the comment on comment info, is this right ?
Hehe, I hope you understand what im asking here… the is my first exploration of SQL, so any tips, hints, would be most welcome….
Thanks loads…
PS: if there anything you don’t understand about what I have written, or what im asking… please say so…
I am trying to build the value off hierarchy that will be later inserted in the linage and Depth column. I am trying to do so using recursion . the rulles for recording the linages as as follows Lineage = parent.Lineage + Ltrim(Str(ParentID,6,0)) + '/'
here is my code below
with BuildHierarchy as ( SELECT AN.AccessID,AN.ChildID,AN.Child,AN.ParentID,AN.CGI D, 1 as Depth,AN.Lineage,AN.node,AN.PercentOwnership, AN.Notes FROM chart_hiera2 as AN WHERE AN.Depth Is Null and AN.AccessID = @accID union all SELECT AN.AccessID,AN.ChildID,AN.Child,AN.ParentID,AN.CGI D,Cast(AN.Depth as smallint) +1 ,Cast(BH.Lineage+ Ltrim(Str(AN.ParentID,6,0)) + '/' as varchar(255)),AN.node,AN.PercentOwnership, AN.Notes FROM chart_hiera2 as AN inner join BuildHierarchy BH on AN.ParentID=BH.ChildID WHERE AN.Depth>=0 AND AN.Lineage Is Not Null AND AN.Depth Is Null and AN.AccessID = @accID)--@accID --and T.AccessID = @accID) select * from BuildHierarchy
but it does not increment Depth or builds Lineage .What am I doing wrong?
Guys, I desperately need your help. what i need to do is call a function getdate to return dates recursively
like so classdate=getdate(class#, repeat, sportcategory,date) while (classdate <yearend) begin classdate=getdate(class#, repeat, sportcategory, classdate) end
I want to use the date returned and keep calling that function till the yearend is reached, to get a bunch of dates declare @startDate datetime
with cteStartDate as ( select x= classdate, repeat, class#, sportcategory, yearend from sports union all select x=getdate( classdate, repeat, yearend), repeat, class#, sportcategory, yearend
from cteStartDate where x < cteStartDate .yearend
)
I tried using cte for this, it only returns one date for everything, as opposed to an array of dates, how do i solve this problem.Any insight will be greatly apprecaited.
Hi there! I have an application that uses stored procedures wuth CTE statements to populate trees from database. Every second I need to populate 100-300 trees each one of them has 15-20 nodes. I checked those procedures with profiler and payed attention that populate procedure with CTE is slower that others (without CTE) per 1000 times! Would procedures with recursion faster than same ones with CTE? I am asking because I read somewhere that CTE is becomes slower while populating little chunks of data. Is that right and I should use recursions?
And second question: here the code -
Code Snippet
;WITH dt (Id, NodeText, PId, State, RowNumber) AS ( SELECT Id, NodeText, PId, State, ROW_NUMBER() OVER(ORDER BY Id) AS RowNumber FROM DataTable WHERE Id = 1
UNION ALL
SELECT d.Id, d.NodeText, d.PId, d.State, ROW_NUMBER() OVER(ORDER BY d.Id) AS RowNumber FROM DataTable AS d INNER JOIN dt ON dt.Id = d.PId )
SELECT * FROM dt
This is how I populate a tree with CTE. Could you give me some example how to do exactly same but with recursion?(without CTE). Thank you!
Hi Y'all,I receive an error while using recursion:The maximum recursion 100 has been exhausted before statement completion. Can someone tell me where i can alter the default value?Thanks in advance
// I need to write a query to extract data from two tables where I save information on my tables in one and the relationship between the tables in the second. //CREATE TABLE [dbo].[tblPages]( // [PageID] [int] NOT NULL, // [PagePath] [varchar](max) , // [MenuName] [nchar](10), // [Directory] [varchar](15)) //CREATE TABLE [dbo].[tblPageRelation]( // [PageRelationshipID] [int] NOT NULL, // [TopPageID] [int] NOT NULL, // [BasePageID] [int] NOT NULL) // What I would like to do is do the following in SQL is a combination of this // SELECT * FROM TblPageRelation PR LEFT OUTER JOIN TblPages P on PR.TopPageID = P.PageID //WHERE P.DIRECTORY = 'MENUBLOCK' UNION SELECT * FROM TblPageRelation PR LEFT OUTER JOIN TblPages P on PR.TopPageID = P.PageID //WHERE P.DIRECTORY = P.DIRECTORY //public void recursivemove (String Directory) // {// Find Rows that Have this Block Name associated with em // For each returned row find the rows that share the same Directory // } //}
I am not sure if select recursion is possible and thought I would throw this challenge to the dba community. The preference would be to create a view that does the work on the backend instead of writing frontend VB code.
Below is script that creates and populates a temp table along with the desired result-set.
create table #myTest ([id] int identity (1,1), [Parent] int , minutes smallint )
insert into #myTest (parent,minutes) values (null,1) insert into #myTest (parent,minutes) values (1,2) insert into #myTest (parent,minutes) values (1,4) insert into #myTest (parent,minutes) values (3,8)
Hi Everybody, I have a table that contains two field Group_ID, ParentGroup_ID this maintains parent Child relation ships between groups now I need a stored procedure in SQL Server that would give the ID's of all Parents of a specified group. it is possible through recursion in stored procedure. I have not much idea of recursion in procedure. Can anybody help, by providing a related sample or code? I would be highly thankful.
I've encountered some strange behavior in a recursive procedure I'mwriting for a bill of materials. First let me ask directly if what Ithink is happening is even possible:It seems like the procedure is not following the recursion in serialorder, but in parallel. In other words, after one instance of theprocedure calls itself, it continues executing lines below therecursion before the recursion is done. Is that possible? I lookedfor SQL Server Options that might deal with recursion or threading butI couldn't find anything.Now let me explain what's happening in terms of the BoM. All the rowsI expect are returned, but not in the correct order. Let's assume thefollowing tree:1|-2| |-5| | |-7| | -8| -6| -9|-3| |-10| |-11| | |-13| | -14| | |-15| | |-16| | -17| -12| -18| -19| -20| |-21| -22-4-23|-24-25-26This is stored in table P using MemberID and ParentID fields. Forexample,MemberID ParentID-------- --------1 NULL2 13 14 15 26 2(etc...)Based on how I wrote the recursion (I will provide the procedurebelow), I would expect output when starting from MemberID of 1 to looklike this:MemberID Depth Sort-------- ----- ----2 1 15 2 27 3 38 3 46 2 59 3 6(etc... basically, the line order of the graphical tree above, or acounter-clockwise traverse around the tree)Instead, I get this (I'll provide the whole thing because I don't seea pattern):MemberID Depth Sort-------- ----- ----2 1 15 2 23 1 210 2 37 3 34 1 36 2 39 3 423 2 48 3 411 2 413 3 512 2 524 3 525 3 618 3 614 3 615 4 719 4 726 4 720 5 816 4 817 4 921 6 922 6 10Call me crazy, but it looks like my tree was parsed in the same orderthat a set of dominos arranged in the same shape would topple. Theonly way I could see that happening is if the recursion is non-linear,allowing both children and siblings to be parsed simultaneously. Itwould also explain why my sort counter didn't increment properly, butthe depth counter is always correct.Now here are the procedures. There's also a Qty column, since this isa BoM after all, but I didn't need to mention it for my illustrationof the problem above.CREATE PROC makebom @root bigint---- This would be called by the client to find all the parts andquantities-- under a specific part (@root)--ASSET NOCOUNT ONCREATE TABLE #result (MemberID bigint, Qty bigint, Depth bigint, sortbigint)EXEC bomrecurse @root, 1, 0SET NOCOUNT OFFSELECT MemberID, Qty, Depth, sort FROM #result ORDER BY sortGOCREATE PROC bomrecurse @root bigint, @depthcounter bigint,@sortcounter bigint---- This is the recursive procedure, called once by makebom, butrecalling-- itself until the whole tree is parsed, filling the #result table--ASDECLARE @memberid bigint, @qty bigint, @nextdepth bigintDECLARE children_cursor CURSOR LOCAL FORSELECT MemberID, Qty FROM PWHERE ParentID = @rootORDER BY MemberIDOPEN children_cursorFETCH NEXT FROM children_cursorINTO @memberid, @qtyWHILE @@FETCH_STATUS = 0BEGINSET @sortcounter = @sortcounter + 1INSERT INTO #result VALUES (@memberid, @qty, @depthcounter,@sortcounter)SET @nextdepth = @depthcounter + 1EXEC bomrecurse @memberid, @nextdepth, @sortcounterFETCH NEXT FROM children_cursorINTO @memberid, @qtyENDCLOSE children_cursorDEALLOCATE children_cursorGOI'm surprised this even worked as well as it did because I'm a newbiewhen it comes to stored procedures and I put this together fromexamples I found around this group, online and in the T-SQL Help. Sofeel free to comment on other aspects of my code or approach, but I'mmost interested in understanding the behavior of this recursion.
I have a table describing a hierarchy structure and the number of levels is very large, say 10000. Can I control the recursive CTE to get the first 1000 levels? Thanks!
I have a bit of an issue with an app I'm working on. The app integrates two different SQL Server applications - both of which employ recursive triggers to some extent. My integration basically serves to establish a link between different tables in the applications, and maintains consistency between the two applications (where common fields exist) by employing INSERT, UPDATE, and DELETE triggers.
In order to prevent infinitely recursive triggers (AppA.TableA's update trigger updates AppB.TableA. AppB.TableA's update trigger updates AppA.TableA...and so on, and so on) I need to be able to somehow selectively prevent these triggers only from executing recursively. For example, if the trigger in AppA is what calls the trigger in AppB, I do not want AppB's trigger to fire (and vice versa).
Further Information:
The apps may be on the same, or different, SQL servers.
I'm fully aware of the database-wide options to disable trigger recursion (ALTER DATABASE), but I can't disable recursion for the balance of the triggers in the databases.
The integration will run on either SQL 2000 or SQL 2005 - and perhaps one server on 2000, and one on 2005 (depending upon the deployment).
I'm perfectly amenable to handling it in the trigger code, if possible, but I'm at a bit of a loss as to how to properly and efficiently manage that.
I know that SQL Server will kill infinitely recursive triggers once it detects them, but that doesn't exactly solve my original problem. Thanks very much for any input you can offer.
I have a table describing a hierarchy structure and the number of levels is very large, say 10000. Can I control the recursive CTE to get the first 1000 levels? Thanks!
Hello my friendsThis is my sql table structureFK = ID int, Empnaam varchar(200), PK = EmpID int With this table, where i insert values, employees can hire other employees. Now i want to see with a function in visual studio who hired who. I get stuck when a person hired more than 1 person....This is my stored procedure :set ANSI_NULLS ON set QUOTED_IDENTIFIER ON GO ALTER PROC [dbo].[ShowHierarchy] ( @Root int ) AS BEGIN SET NOCOUNT ON DECLARE @EmpID int, @EmpNaam varchar(30) SET @EmpNaam = (SELECT EmpNaam FROM dbo.Emp WHERE EmpID = @Root) PRINT REPLICATE('-', @@NESTLEVEL * 4) + @EmpNaam SET @EmpID = (SELECT MIN(EmpID) FROM dbo.Emp WHERE ID = @Root) WHILE @EmpID IS NOT NULL BEGIN EXEC dbo.ShowHierarchy @EmpID SET @EmpID = (SELECT MIN(EmpID) FROM dbo.Emp WHERE ID = @Root AND EmpID > @EmpID) END END Thanks in advance!Grtz
I would like to return the nearest date of Table B in my table like for
ID W001 in table B should return ID A002 CreatedDatetime: 2014-06-03 20:05:48.000 ID W002 in table B should return ID A004 CreatedDatetime: 2014-06-04 01:05:48.000
There's an SP that in effect returns a table -- it loops and executesstatements like SELECT @field1, @Field2, @Field2Can I capture its results in a table? I know that if it were a FUNCTIONthat returned a table, that would be simple:INSERT ResultsTable SELECT * FROM dbo.Function (@Param1, @Param2)But how to do that if the code is a procedure rather than a function?
Hi, I'm new to the forums, so hopefully I'm at the right place with my question...
Suppose I have a user-defined type in C#, which stands for simple point in 2D (let's call it Point). The type consists of two integer fields that represent the X and Y coordinate of the point. To make things a little more complicated, I want to store my values compressed using an algorithm, so I can't directly access X and Y without using a decompression algorithm.
I also have a table (PointTable), it's only column is called Data and is of type Point.
Now, writing and executing a simple query like
SELECT Data.ToString() FROM PointTable is no problem at all.
What I want to do, is to be able to retrieve a table filled with the X and Y coordinates, so something like this:
SELECT PointX, PointY FROM GetTable() where GetTable creates a table with columns PointX and PointY.
The function GetTable() should be implemented in C#, and work something like this: iterate through all Point values, decompress them, and create a new row from each Point.
I hope my intentions are clear and thanks for your help in advance!
IF @art <>'/' INSERT INTO @result SELECT dbo.CD.CDCoverURL AS ' ', dbo.CD.CDTitle AS 'CD Title',cd.cdtype as 'Section', convert(varchar,cd.cddate,106) as 'Release Date', dbo.Label.Label, dbo.Shelf.Shelf FROM artist,cd,label,shelf,cdtrack,artisttrack,track WHERE artist.artistid=artisttrack.artistid and cd.cdid=cdtrack.cdid and track.trackid=cdtrack.trackid and label.labelid=cd.labelid and shelf.shelfid=cd.shelfid and artisttrack.trackid=track.trackid and artist.artist=@art Group by dbo.CD.CDCoverURL, dbo.CD.CDTitle, dbo.CD.CDType, dbo.CD.CDDate, dbo.Label.Label, dbo.Shelf.Shelf
if @cd <>'/' insert into @result SELECT dbo.CD.CDCoverURL AS ' ', dbo.CD.CDTitle AS 'CD Title',cd.cdtype as 'Section', convert(varchar,cd.cddate,106) as 'Release Date', dbo.Label.Label, dbo.Shelf.Shelf FROM artist,cd,label,shelf,cdtrack,artisttrack,track where artist.artistid=artisttrack.artistid and cd.cdid=cdtrack.cdid and track.trackid=cdtrack.trackid and label.labelid=cd.labelid and shelf.shelfid=cd.shelfid and artisttrack.trackid=track.trackid and cd.cdtitle=@cd Group by dbo.CD.CDCoverURL, dbo.CD.CDTitle, dbo.CD.CDType, dbo.CD.CDDate, dbo.Label.Label, dbo.Shelf.Shelf
if @tra <> '/' insert into @result SELECT dbo.CD.CDCoverURL AS ' ', dbo.CD.CDTitle AS 'CD Title',cd.cdtype as 'Section', convert(varchar,cd.cddate,106) as 'Release Date', dbo.Label.Label, dbo.Shelf.Shelf FROM artist,cd,label,shelf,cdtrack,artisttrack,track where artist.artistid=artisttrack.artistid and cd.cdid=cdtrack.cdid and track.trackid=cdtrack.trackid and label.labelid=cd.labelid and shelf.shelfid=cd.shelfid and artisttrack.trackid=track.trackid and track.track=@tra Group by dbo.CD.CDCoverURL, dbo.CD.CDTitle, dbo.CD.CDType, dbo.CD.CDDate, dbo.Label.Label, dbo.Shelf.Shelf
if @gen <>'/' insert into @result SELECT dbo.CD.CDCoverURL AS ' ', dbo.CD.CDTitle AS 'CD Title',cd.cdtype as 'Section', convert(varchar,cd.cddate,106) as 'Release Date', dbo.Label.Label, dbo.Shelf.Shelf FROM artist,cd,label,shelf,cdtrack,artisttrack,track where artist.artistid=artisttrack.artistid and cd.cdid=cdtrack.cdid and track.trackid=cdtrack.trackid and label.labelid=cd.labelid and shelf.shelfid=cd.shelfid and artisttrack.trackid=track.trackid and cd.cdtype=@gen Group by dbo.CD.CDCoverURL, dbo.CD.CDTitle, dbo.CD.CDType, dbo.CD.CDDate, dbo.Label.Label, dbo.Shelf.Shelf
if @cdate<>'01/01/1900' insert into @result SELECT dbo.CD.CDCoverURL, dbo.CD.CDTitle, dbo.CD.CDType, dbo.CD.CDDate, dbo.Label.Label, dbo.Shelf.Shelf FROM artist,cd,label,shelf,cdtrack,artisttrack,track where artist.artistid=artisttrack.artistid and cd.cdid=cdtrack.cdid and track.trackid=cdtrack.trackid and label.labelid=cd.labelid and shelf.shelfid=cd.shelfid and artisttrack.trackid=track.trackid and cd.cddate=@cdate Group by dbo.CD.CDCoverURL, dbo.CD.CDTitle, dbo.CD.CDType, dbo.CD.CDDate, dbo.Label.Label, dbo.Shelf.Shelf
if @label<>'/' insert into @result SELECT dbo.CD.CDCoverURL, dbo.CD.CDTitle, dbo.CD.CDType, dbo.CD.CDDate, dbo.Label.Label, dbo.Shelf.Shelf FROM artist,cd,label,shelf,cdtrack,artisttrack,track where artist.artistid=artisttrack.artistid and cd.cdid=cdtrack.cdid and track.trackid=cdtrack.trackid and label.labelid=cd.labelid and shelf.shelfid=cd.shelfid and artisttrack.trackid=track.trackid and label.label=@label Group by dbo.CD.CDCoverURL, dbo.CD.CDTitle, dbo.CD.CDType, dbo.CD.CDDate, dbo.Label.Label, dbo.Shelf.Shelf return end --------------------------------------------------------------------- upon running executing this function with valid values i am not getting any results. anything is wrong? thank you,
I have to work with some configuration data that is stored in rows as a comma separated values. Something like this:
Key1 A,1,Z,0;B,2,Y,9;C,,8,X;
Key2 Alpha,101;Beta,102;
Each group of data is separated by a semicolon and each value by a comma. The quantity of values may vary from one key to the other. Over this values sometimes I need to run some selects, so I went with the idea to get it as a table using CLR.
There I find the first problem: I didn't find a way to return a "variable" column with a CLR function, I had to create a SP. Ok, now I execute spGetConfigurationAsTable 'Key1' and I can obtain something like this:
A 1 Z 0
B 2 Y 9
C 3 X 8
But I'm faced with a second problem: How can I run a query over this? I didn't find a way to run a query over an output of a SP. And I can't INSERT the result into a temporary table because I cannot CREATE the table static (remember the columns may differ from one configuration to the other).
So, it seemed a pretty simple task and a neat solution, but I'm kinda stuck. Is there a way to run a query over the SP output? Or is there a way to have a variable table output from a CLR UDF?
Here is the code of the CLR SP I use to obtain the data, and also the (non-working) CLR user defined function.
THANKS!
Code Snippet public partial class StoredProcedures { [Microsoft.SqlServer.Server.SqlProcedure] public static void spGetConfigurationAsTable(string Key) { SqlConnection conn = new SqlConnection("Context Connection=true"); string SqlCmd = string.Format("SELECT Value FROM Configuracion WHERE [Key] = '{0}' ", Key); SqlCommand cmd = new SqlCommand(SqlCmd, conn); conn.Open(); string Value = Convert.ToString(cmd.ExecuteScalar()); if (Value.Length > 0) { char SeparatorRow = ';'; char SeparatorColumn = ','; if (Value.Split(SeparatorRow)[0].Split(SeparatorColumn).Length > 35) return; StringBuilder SqlCreate = new StringBuilder("DECLARE @Output TABLE ("); for (int i = 0; i < Value.Split(SeparatorRow)[0].Split(SeparatorColumn).Length; i++) { SqlCreate.AppendFormat("[{0}] varchar(50),", Convert.ToChar(65 + i)); } SqlCreate.Remove(SqlCreate.Length - 1, 1); SqlCreate.AppendLine(");"); StringBuilder SqlInsert = new StringBuilder(); foreach (string row in Value.Split(SeparatorRow)) { if (row.Length > 0) { SqlInsert.Append("INSERT INTO @Output VALUES ("); // busca las diferentes "columns" ~ Charly foreach (string column in row.Split(SeparatorColumn)) { SqlInsert.AppendFormat("'{0}',", column); } SqlInsert.Remove(SqlInsert.Length - 1, 1); SqlInsert.AppendLine(");"); } } string SqlSelect = "SELECT * FROM @Output;"; cmd.CommandText = SqlCreate.ToString() + SqlInsert.ToString() + SqlSelect; SqlDataReader reader = cmd.ExecuteReader(); SqlContext.Pipe.Send(reader); reader.Close(); reader.Dispose(); } conn.Close(); conn.Dispose(); cmd.Dispose(); } };
Code Snippet public partial class UserDefinedFunctions { [Microsoft.SqlServer.Server.SqlFunction] public static IEnumerable fGetConfigurationAsTable(string Key) { SqlConnection conn = new SqlConnection("Context Connection=true"); string SqlCmd = string.Format("SELECT Value FROM Configuracion WHERE [Key] = '{0}' ", Key); SqlCommand cmd = new SqlCommand(SqlCmd, conn); conn.Open(); string Value = Convert.ToString(cmd.ExecuteScalar()); conn.Close(); conn.Dispose(); cmd.Dispose(); DataTable dt = new DataTable(); if (Value.Length > 0) { char SeparatorRow = ';'; char SeparatorColumn = ','; if (Value.Split(SeparatorRow)[0].Split(SeparatorColumn).Length > 35) { // throw exception } string ColumnName; for (int i = 0; i < Value.Split(SeparatorRow)[0].Split(SeparatorColumn).Length; i++) { ColumnName = string.Format("[{0}] varchar(50),", Convert.ToChar(65 + i)); dt.Columns.Add(ColumnName, Type.GetType("System.String")); } foreach (string row in Value.Split(SeparatorRow)) { if (row.Length > 0) { dt.Rows.Add(row.Split(SeparatorColumn)); } } } return dt.Rows; } };
It seemed quite easy at first glance. I Built it up via string concatenation and thought to execute the dynamic sql with sp_exec and get the result. As I don't like dynamic sql I was wondering If there is any other way..
I have a table tblFriends:UserCodeOwner FriendCode5 545 1235 4785 49054 5123 5478 5478 500490 5490 500500 478500 490500 600600 500As you can see I store each relation twice, i've done that because now I can create a clustered index on UserCodeOwner for faster searching.What I want is the following:I want to count how many steps it takes to get from one user to another via their relations and also via which usercode it goes.so: from 5 to 123 is one step.5-123from 5 to 500 is 2 steps via either 478 or 490I want to get a result like this:5-478-500and5-490-500from 5 to 600 is 3 steps:5-478-500-6005-490-500-600Does anyone have a good start for me on how im able to return such results and how I can search through the table most effecively?
Hi,I have a employee attendance table, and Im trying to return the dates on which an employee is absent. There are no table entries for an employee who is absent on a particular day. So can anyone please help on how i can return the dates on which an employee is absent. Any help will be greatly appreciated, Thanks,Najla.
I have two tables. In tblUsers is all userdata. In table tblMoreInfo is some info on a user (0-15 records).Now I want to select tblUsers.username and tblUsers.usercode and the matching top 1 row tblMoreInfo.schoolname (top 1 based on tblMoreInfo.createdate) IF IT EVENT EXISTS from tblMoreInfo. If no matching record exists I want the value NULL to be returned for the schoolname...In all cases tblUsers.username must be unique (and I cant use the distinct keyword as im already using the row_number() function.Any help?Thanks!
I am trying to created a stored procedure/query to return all fields from any of my 43 look-up tables in my database. I have all of my look-up table names listed in a VB grid. I want the user to select a particular table, click edit (which pass's the table name) and have one stored procdure return all of the field in the table and populate them in a second VB form with the fields listed in a new grid.
Can one pass the "SQL string" to excute/ create a temp table.... A regular SP requires a specife table name to query from. Is there a way to do this without creating a temp table
I need to do something sort of like the DESCRIBE function in MySQL. I need to return the table structure, AND the first row from each column sort of as an example of the data in each column.
then i would just need to run this query on each of my tables...
I've been tearing my hair out over this UDF. The code works within astored procedure and also run ad-hoc against the database, but does notrun properly within my UDF. We've been using the SP, but I do need aUDF instead now.All users, including branch office, sub-companies and companies and soon up the lines are in the same table. I need a function which returnsa row for each level, eventually getting to the master company all theway at the top, but this UDF acts as though it can't enter the loop andonly inserts the @userID and @branchID rows. I have played with theWHILE condition to no avail.Any ideas on what I am missing?(Running against SQL Server 2000)---------------------------------------------------ALTER FUNCTION udfUplineGetCompany (@userID int)RETURNS @upline table (companyID int, companyname varchar(100), infovarchar(100))ASBEGINDECLARE @branchID intDECLARE @companyID intDECLARE @tempID int--Insert the original user dataINSERT INTO @uplineSELECT tblusersid, companyname, 'userID'FROM tblusersWHERE tblusersid = @useridSELECT @branchID = tblUsers.tblUsersIDFROM tblUsersINNER JOIN tblUsersUsersLnkON tblUsers.tblUsersID = tblUsersUsersLnk.tblUsersID_ParentWHERE tblUsersUsersLnk.tblUsersID_Child = @userid--Up one levelINSERT INTO @uplineSELECT tblusersid, companyname, 'branchID'FROM tblusersWHERE tblusersid = @branchidSET @tempID = @branchIDWHILE @@ROWCOUNT <> 0BEGINSELECT @companyID = tblUsers.tblUsersIDFROM tblUsersINNER JOIN tblUsersUsersLnkON tblUsers.tblUsersID = tblUsersUsersLnk.tblUsersID_ParentWHERE tblUsersUsersLnk.tblUsersID_Child = @tempIDAND tblUsersId <> 6--Insert a row for each level upINSERT INTO @uplineSELECT tblusersid, companyname, 'companyID'FROM tblusersWHERE tblusersid = @companyIDSET @tempID = @companyIDENDRETURNEND
Sp which inserts inforamtion into a table works fine. The trigger on that table which then inserts information into another table works fine. Only problem is that the SP will not return anything to Visual Basic.. Anyone know how to fix it?
SPbob INsert into b values(1,1,2,2) select 0
(this is a cut up version of the sp just to show about the way it is formated) Please help.