I've got a fairly large hierarchy table and I'm trying to put together a query to find the lowest level descendants of the hierarchy. I think there must be some way to use the "Breadth-first" approach that's stated in the MSDN technet sites about SQL Server HierarchyID but i'm not sure how to write the necessary T-SQL to traverse that. I know I can get all the descendants of a parent node like this
SELECT * FROM AdventureWorks2012.HumanResources.Employee WHERE OrganizationNode.IsDescendantOf(@ParentNode) = 1
However, this query returns all levels for that parent's branch. If I just wanted list of employees that were at the lowest level of the branch(es) for this parent node, how would I do this?
Does anyone know how to query a field in a table where it contains anASCII code >= 128 - without looping through every field for everyrecord in table (using charindex)?Ex of char I would like to find: ü which is char(252)
I have a script that creates these spin off tables (used for lightning fast access) on a near daily basis. But it is possible the table does not exist for that day - in which the script need to check one day back - so on and so forth until finding the most recently created table.
The script I have written fails with overflow error. I was hoping someone could tell me the correct syntax to accomplish this and also why i recieve this overflow error...
Code:
Dim str_SQL_Asset_1 daysBack = 1 tblFound = FALSE Dim xbl_Holdings_date Dim xMonth Dim xDay xbl_Holdings_date = date() If Len(Month(xbl_Holdings_date))=1 Then xMonth = "0" & Month(xbl_Holdings_date) Else xMonth = Month(xbl_Holdings_date) End If If Len(Day(xbl_Holdings_date))=1 Then xDay = "0" & Day(xbl_Holdings_date) Else xDay = Day(xbl_Holdings_date) End If
IF MM_checkCmd.EOF Then xbl_Holdings_date = (xbl_Holdings_date - daysBack) daysBack = daysBack + 1 tblFound = FALSE ELSE tblFound = TRUE MM_checkCmd.CLOSE() SET MM_checkCmd = Nothing END IF loop
The goal of this snippet is simply to identify and set the value for the existing table name. An example table name would be "xbl_Holdings_2006_12_10".
I could have posted this question in the VB forum but I would like to push as much of the work onto SQL as possible and also - this sort of operation is more likely to be required of a dba imo.
I'm trying to find the primary key on a given table in SQL Server 2000 using SQL. I'm querying the sysobjects table to find a given table, and then querying the sysindexes table. I've ALMOST found what I'm looking for. I see the indexes and columns etc. on the tables in the database, I just don't see the field that indicates that the index is the primary key. Can anyone help? Thanks, Alex
I'm fairly new to sql.I've got a database that all I want to do is view some records fromsome tables. But the thing is, I do not know the table names ortheir relationships.I've got access to the database thru query analyzer. Can someoneassist me in gettign the correct statements that will allow me to findout what tables exist in the database.
When I open a table and need to make a change within a particular record...
How do I find the particular row that I am looking for? I seem to have to scroll through 600 records to find the one I need. I've found a search and replace function but it doesn't seem to work.
Need some suggestions on what to check or look for.My stored proc is not finding the table in the sql db. This is the error...Invalid object name 'tblServRec'I use the same function to pass in an arraylist and the sp name for another sp and that one works ok.The sp is the same as another one except for the table name and that one works ok.The sp works fine on my local machine. It finds the table ok. But when I try it on the server, it doesn't work.I have checked permissions, and they are the same for all tables, even the one that the other sp works ok on the server.Here is the sp if that will help.....CREATE PROCEDURE dbo.deleteServRec @fldNum INT ASBEGIN DECLARE @errCode INT DELETE FROM tblServRec WHERE fldNum = @fldNum SET @errCode = 0 RETURN @errCode HANDLE_APPERR: SET @errCode = 1 RETURN @errCodeENDGOThanks all,Zath
Is there any way to find the time when the last DDL was happened in a table? For example: The time when the new column(s) were added into a table or changed the datatype.
Is there a way to find out when the last modification or change to data in a table occured ? How about the last change of a view ?
We'd like to be able to extract data to another table based on a view. Then, at a later date, check to see if the first table or view has changed since the last extract. If not, then we don't need to re-extract the data, we know it hasn't changed.
How the client wants me to write a query, that will find "suspected abuse of accounts" - defined by being successful logins made within one hour from at least 3 different IPs.
So I need to check for events, that are within one hour from each other (datecreated field) and have the same userID - and EventTypeId - but at least 3 different IPs.
Maybe it's just late in the day or I am overworked, but I cant seem to find an effective way to approach this.
Hi,I want to find out in my SP the filegroup associated with a particulartable? I was not able to establish the relationship between sysobjectsand sysfilegroups table. Is there any other way to find filegroup of atable in T_SQL?Also lets say there are 3 dtatfiles in a filegroup 'FG1' and table'xyz' is created on filegroup 'FG1' - Is there any way to find out thedatafile's names on which table xyz's data is scattered?Thanks in Advance,Subodh
We have an application that accesses a particular table, but it isnever updated. Without stepping through the complex application code,is there a method of logging when a particular table is accessed?
OK, this should be an easy one but my brain isn't quite working right now.
I have a table, we'll call Table1 like so:
ProductID Supplier Cost 12345 A 14.50 12345 B 13.49 12345 C 12.00 43222 A 15.00 43222 B 15.21 43222 C 13.99 12312 B 14.00 15421 A 21.99 15421 C 20.00
And I want to Get the name of the Supplier with the Lowest cost, I know I can go like:
SELECT ProductID, MIN(Cost) FROM Table1 GROUP BY ProductID
and get the lowest cost, but what would be the most effiecent way to get all three fields returned by the query? I need the ProductID, Supplier and Cost.
@AppId AS Application_Id , MB.POLICY_ID AS Policy_Id , MH.BFN_CHG_DATEAS Date_Of_Disinvestment , AD.X_INVEST_AMT AS Original_Investment_Value , MB.TOTAL_AMOUNT AS Encashment_Value , WH.TOT_COMMISSION AS Top-Up_Commission
FROM: I select from lot of table, as specified from my select statement
My Aliases returns just one values, of which that's what I am expecting, so I need to make a comparison between Original_Investment_Value and (Encashment_Value + Top-Up_Commision), and return the lowest value
Is there a more elegant way to do the following?...declare @d1 datetime, @d2 datetimeset @d1 = '2005-01-01'set @d2 = '2005-02-01'selectcasewhen datediff(dd,@d2,@d1)is nullthen coalesce(@d1, @d2)when (datediff(dd,@d2,@d1)> 0)then @d2else @d1endCheers,..N
Hi, this seems to be an easy question but I can't find a quick answer to it. I have an asp page that communicates with a database and I want the following example to work...
Insert 5 records into the DB with primary keys 1-5. Remove record with key number 2.
Now, if I insert a new record I want it to take the smallest available key number (in this case number 2). This will save space in the database and keep the key numbers from increasing forever.
Does auto increment work like this? If not, how do I do it?
I'm trying to find out less than 10% in revenue accounts from a table. Below is a snapshot. Basically, I want to add Revenue mix column in the table using procedure.
I have a table which maps two related IDs. That table has 3 columns: ID, BHID & EPID. I need to find all of the BHIDs where the EPID is unique. It seems easy enough, but I keep going in circles..
USE [CGB] GO /****** Object: Table [dbo].[ePID_BHID] Script Date: 04/15/2015 15:48:14 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON
Our company is a proffesional deticated bullet proof server and general server provider in china. If you're looking for a reliable and long term cooperation bp server provider, it deservers you to read our company file to know more about us.
I'm using sql express 2005. I need help with buliding a view.
I'm trying to join two tables and then, if duplicate ID's exist, retrieve the row with the lowest value in a specific column.
For instance:
TableHousehold:
ID Name Status
001 The Smith€™s A
002 The Jone€™s A
003 The Adam€™s A
004 The Grant€™s A
TableResidents
Pk HouseholdID ResidentID Name Gender
1 001 1 Mary Smith F
2 001 2 Jason Smith M
3 001 3 Rachel Smith F
4 002 1 Mike Jones M
5 002 2 Sara Jones F
6 003 2 Erik Adams M
The resident ID is auto increment and assigned by the server. It is possible for resident 1 for each household to have been deleted. It is also possible that a household does not contain any residents. Therefore, I wish to join these tables and return this:
ID HouseHoldName Status ResidentName Gender
001 The Smith€™s A Mary Smith F
002 The Jone€™s A Mike Jones M
003 The Adam€™s A Erik Adams M
004 The Grant€™s A null null
There are other columns in both tables that I will want to join, but for simplicity, the above example illustrates my need.
I was able to accomplish this by creating two views. But I€™d like to try and do this in one.
This function will generate all DELETE statements in correct order to perform a CASCADING delete. For self-joined tables, it will generate the T-SQL code to "unwind" the table, also in correct order!CREATE FUNCTION dbo.fnCascadingDelete ( @Schema NVARCHAR(128) = NULL, @Table NVARCHAR(128) = NULL ) RETURNS@Return TABLE ( RowID INT PRIMARY KEY CLUSTERED, IsSelfJoin TINYINT NOT NULL, HasPk TINYINT NOT NULL, [SQL] NVARCHAR(4000) NOT NULL ) AS BEGIN DECLARE@Constraints TABLE ( RowID INT NOT NULL, Indent SMALLINT NOT NULL, [Catalog] NVARCHAR(128) NOT NULL, [Schema] NVARCHAR(128) NOT NULL, [Table] NVARCHAR(128) NOT NULL, [Column] NVARCHAR(128), pkCatalog NVARCHAR(128), pkSchema NVARCHAR(128), pkTable NVARCHAR(128), pkColumn NVARCHAR(128), pkType NVARCHAR(128), pkSize INT, IsSelfJoin TINYINT NOT NULL, HasPk TINYINT NOT NULL )
INSERT@Constraints ( RowID, Indent, [Catalog], [Schema], [Table], [Column], pkCatalog, pkSchema, pkTable, pkColumn, pkType, pkSize, IsSelfJoin, HasPk ) SELECTRowID, Indent, [Catalog], [Schema], [Table], [Column], pkCatalog, pkSchema, pkTable, pkColumn, pkType, pkSize, SelfJoin, CASE WHEN [Column] IS NULL THEN 0 ELSE 1 END FROMdbo.fnTableTree(@Schema, @Table)
IF @@ROWCOUNT = 0 RETURN
DECLARE@SQL TABLE ( ID INT IDENTITY(1, 1), RowID INT PRIMARY KEY CLUSTERED, IsSelfJoin TINYINT NOT NULL, HasPk TINYINT NOT NULL, [SQL] NVARCHAR(4000) NOT NULL )
DECLARE@Unwind TABLE ( RowID INT NOT NULL, StepID INT IDENTITY(0, 1) PRIMARY KEY NONCLUSTERED, [SQL] NVARCHAR(4000) )
WHILE NOT EXISTS (SELECT * FROM @SQL WHERE RowID = 1) BEGIN SELECT TOP 1@RowID = c.RowID, @ID = c.RowID, @Indent = c.Indent, @TSQL = N'', @EndSQL = N'', @IsSelfJoin = c.IsSelfjoin, @HasPk = c.HasPk FROM@Constraints AS c LEFT JOIN@SQL AS s ON s.RowID = c.RowID WHEREs.RowID IS NULL ORDER BYc.Indent DESC, c.RowID DESC
WHILE @ID > 0 BEGIN IF @Indent = 0 SELECT@RowSQL = N'DELETE t' + CAST(@RowID AS NVARCHAR(12)), @RowSQL = @RowSQL + N' FROM ' + QUOTENAME(c.[Catalog]) + N'.' + QUOTENAME(c.[Schema]) + N'.' + QUOTENAME(c.[Table]) + N' AS t' + CAST(@ID AS NVARCHAR(12)), @EndSQL = N' WHERE t' + CAST(@ID AS NVARCHAR(12)) + '.' + QUOTENAME(COALESCE(c.[Column], '%0')) + N' = ''%1''', @IsSelfJoin = @IsSelfJoin | c.IsSelfJoin FROM@Constraints AS c WHEREc.RowID = @ID ELSE SELECT@RowSQL = N' INNER JOIN ' + QUOTENAME(c.[Catalog]) + N'.' + QUOTENAME(c.[Schema]) + N'.' + QUOTENAME(c.[Table]), @RowSQL = @RowSQL + N' AS t' + CAST(@ID AS NVARCHAR(12)) + N' ON t' + CAST(@ID AS NVARCHAR(12)) + N'.' + QUOTENAME(c.[Column]), @pkColumn = QUOTENAME(c.pkColumn), @IsSelfJoin = @IsSelfJoin | c.IsSelfJoin FROM@Constraints AS c WHEREc.RowID = @ID
SELECT TOP 1@ID = c.RowID, @Indent = c.Indent, @RowSQL = @RowSQL + N' = t' + CAST(c.RowID AS NVARCHAR(12)) + N'.' + @pkColumn, @IsSelfJoin = @IsSelfJoin | c.IsSelfJoin FROM@Constraints AS c WHEREc.RowID < @ID AND c.Indent < @Indent ORDER BYc.Indent DESC, c.RowID DESC
INSERT@Stage (Lvl, RowKey) SELECT@Lvl, t.' + QUOTENAME(@pkColumn) + ' FROM' + QUOTENAME(@Catalog) + '.' + QUOTENAME(@Schema) + '.' + QUOTENAME(@Table) + ' AS t INNER JOIN@Stage AS s ON s.RowKey = t.' + QUOTENAME(@Column) + ' AND s.Lvl = @Lvl - 1 LEFT JOIN@Stage AS cr ON cr.RowKey = t.' + QUOTENAME(@pkColumn) + ' WHEREcr.RowKey IS NULL END SELECT ''DELETE FROM ' + QUOTENAME(@Catalog) + '.' + QUOTENAME(@Schema) + '.' + QUOTENAME(@Table) + ' WHERE ' + QUOTENAME(@pkColumn) + ' = '' + QUOTENAME(RowKey, '''''''') FROM @Stage WHERE RowID > 0 ORDER BY RowID DESC'
INSERT@Unwind ( RowID, [SQL] ) VALUES( @RowID, @RowSQL ) END END
INSERT@Return ( RowID, IsSelfJoin, HasPk, [SQL] ) SELECTs.ID, s.IsSelfJoin, s.HasPk, CASE WHEN u.RowID IS NULL THEN s.[SQL] ELSE u.[SQL] END FROM@SQL AS s LEFT JOIN@Unwind AS u ON u.RowID = s.RowID ORDER BYs.ID, u.StepID