Quantcast
Channel: Transact-SQL forum
Viewing all 23857 articles
Browse latest View live

Last executed queries for a specific database

$
0
0
Hi to all,
I am using below query to find last executed queries. but  I want to filter only the records from a particular Database. How do I do it? 
SELECT deqs.last_execution_time AS [Time], dest.text AS [Query]
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
CROSS APPLY sys.tables as tab
where tab.type like 'u'
ORDER BY deqs.last_execution_time DESC
Thanks

TSQL table create script automatically by passing schema and table name

$
0
0

I have scenario like this I have to create one database tables , view and stored procedure  script  and change column data type like if any column have datatype int then I need to convert it as Integer, Varchar to text …… by  passing the name table schema and table name , if any table have Pk and fk and constraint I need that script also

e.g

USE [AdventureWorksDW]

GO


CREATETABLE [fact].[FactFinance](

            [TimeKey] [int]NULL,

            [OrganizationKey] [int]NULL,

            [DepartmentGroupKey] [int]NULL,

            [ScenarioKey] [varchar(100)]  notNULL,

            [AccountKey] [int]NULL,

            [Amount] [float]NULL

)ON [PRIMARY]

GO

ALTERTABLE [fact].[FactFinance] WITHCHECK ADD  CONSTRAINT [FK_FactFinance_DimAccount]FOREIGNKEY([AccountKey])

REFERENCES [Fact].[DimAccount]([AccountKey])

GO

ALTERTABLE [Fact].[FactFinance]CHECKCONSTRAINT [FK_FactFinance_DimAccount]

GO

ALTERTABLE [Fact].[FactFinance] WITHCHECK ADD  CONSTRAINT [FK_FactFinance_DimDepartmentGroup]FOREIGNKEY([DepartmentGroupKey])

REFERENCES [fact].[DimDepartmentGroup]([DepartmentGroupKey])

GO

ALTERTABLE [fact].[FactFinance]CHECKCONSTRAINT [FK_FactFinance_DimDepartmentGroup]

GO

ALTERTABLE [Fact].[FactFinance] WITHCHECK ADD  CONSTRAINT [FK_FactFinance_DimOrganization]FOREIGNKEY([OrganizationKey])

REFERENCES [fact].[DimOrganization]([OrganizationKey])

GO

ALTERTABLE [Fact].[FactFinance]CHECKCONSTRAINT [FK_FactFinance_DimOrganization]

GO

ALTERTABLE [dbo].[FactFinance] WITHCHECK ADD  CONSTRAINT [FK_FactFinance_DimScenario]FOREIGNKEY([ScenarioKey])

REFERENCES [fact].[DimScenario]([ScenarioKey])

GO

ALTERTABLE [Fact].[FactFinance]CHECKCONSTRAINT [FK_FactFinance_DimScenario]

GO

ALTERTABLE [Fact].[FactFinance] WITHCHECK ADD  CONSTRAINT [FK_FactFinance_DimTime]FOREIGNKEY([TimeKey])

REFERENCES [Fact].[DimTime]([TimeKey])

GO

ALTERTABLE [Fact].[FactFinance]CHECKCONSTRAINT [FK_FactFinance_DimTime]

GO

I need this table script generate automatically by passing the schema name and table name  as

CREATETABLE [Fact].[FactFinance](

            [TimeKey] [iteger]NULL,

            [OrganizationKey] [integer]NULL,

            [DepartmentGroupKey] [integer]NULL,

            [ScenarioKey]  text,

            [AccountKey] [integer]NULL,

            [Amount] [Real]NULL

)ON [PRIMARY]

along with FK and Pk any help 



Encrypt and Decrypt not working properly

$
0
0

 ----[EncryptString]
CREATE FUNCTION [dbo].[EncryptString](@strInputString [nvarchar](4000), @strKey [nvarchar](4000))
RETURNS [nvarchar](4000) WITH EXECUTE AS CALLER
AS 
EXTERNAL NAME [HICLR].[HICLR.TripleDES].[EncryptString]

---[DecryptString]
CREATE FUNCTION [dbo].[DecryptString](@strDecryptString [nvarchar](4000), @strKey [nvarchar](4000))
RETURNS [nvarchar](4000) WITH EXECUTE AS CALLER
AS 
EXTERNAL NAME [HICLR].[HICLR.TripleDES].[DecryptString]



--Testing
DECLARE @Key NVARCHAR(4000) = 'ABCD';
DECLARE @EncryptedAccountNumber NVARCHAR(4000), 
        @DecryptedAccountNumber NVARCHAR(4000),
   @EncryptedAccountNumber2 NVARCHAR(4000), 
   @DecryptedAccountNumber2 NVARCHAR(4000);

SELECT TOP 1 @EncryptedAccountNumber = CAST(AccountNumber AS VARCHAR(4000)) FROM Info
PRINT @EncryptedAccountNumber;

SELECT @DecryptedAccountNumber = dbo.DecryptString(@EncryptedAccountNumber, @Key);
PRINT @DecryptedAccountNumber;
---works fine for above 2 



--Now, when i want to take @DecryptedAccountNumber and try to encrypt back, it gives mis match String 
SELECT @EncryptedAccountNumber2 = EncryptString(@DecryptedAccountNumber, @Key);
PRINT @EncryptedAccountNumber2;



--and when i run below, i get error shown below 
SELECT @DecryptedAccountNumber2 = DecryptString(@EncryptedAccountNumber2, @Key);
PRINT @DecryptedAccountNumber2;

--Msg 6522, Level 16, State 2, Line 9
--A .NET Framework error occurred during execution of user-defined routine or aggregate "DecryptString": 
--System.ApplicationException: CLR Function 'DecryptString' failed: Bad Data.
-- ---> System.Security.Cryptography.CryptographicException: Bad Data.

--System.Security.Cryptography.CryptographicException: 
--   at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
--   at System.Security.Cryptography.Utils._DecryptData(SafeKeyHandle hKey, Byte[] data, Int32 ib, Int32 cb, Byte[]& outputBuffer, Int32 outputOffset, PaddingMode PaddingMode, Boolean fDone)
--   at System.Security.Cryptography.CryptoAPITransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount)
--   at WorkbenchCLR.TripleDES.DecryptBytes(Byte[] bytDecryptBuffer, String strKey)
--   at WorkbenchCLR.TripleDES.DecryptString(String strDecryptString, String strKey)
--System.ApplicationException: 
--   at WorkbenchCLR.TripleDES.DecryptString(String strDecryptString, String strKey)
--.

please help on how to resolve this issue

OPENQUERY Issue/ Linked Server

$
0
0

we have created Linked Server from ServerA to ServerB. Both are SQL server. I have to fetch some data from ServerB using linked server. I have written below code (I have not provided all code as it is very big piece of code).

Linked server is working fine, I can query tables like: Select * from CAS.dbo.vSber. But when I execute below query, I am getting this strange error. I also executed this query directly on ServerB and it is executing successfully. 

Msg 11525, Level 16, State 1, Procedure sp_describe_first_result_set, Line 1
The metadata could not be determined because statement 'Insert into #v_temp.

Metadata discovery only supports temp tables when analyzing a single-statement batch.

Can someone help?

                     

declare @dtsql NVARCHAR(MAX)
SET @dtsql = N'
       SELECT * FROM
    OpenQuery(CAS,''

Create Table #v_temp
(
RecordID int,
MachineName varchar(256),
Time datetime
)

Insert into #v_temp
SELECT vs.RecordID, vs.MachineName, Time
FROM [CAS].dbo.v_StatusMessage vs 
JOIN [CAS].dbo.v_StatMsgInsStrings vsi on vs.RecordID = vsi.RecordID
WHERE MessageID = 39997
AND InsStrValue = ''Evt_Error''


-- MORE TSQL Statement
-- SELECT and UPDATE TSQL
-- More Temptable and Insert
-- Final Select 

       '')'

exec sp_executesql @dtsql

Move a bunch of tables to a different database

$
0
0

Hi,

I'm wondering if there is any simple way to wright a script for moving a list of tables into another database?

Example:

SELECT TableName FROM List  - gives me a list of tables

...that I would like to move into a different database, like:

select * into HistoricDataBase.dbo.TableName from DataBase.dbo.TableName

Drop table DataBase.dbo.TableName 

It's more than 500 tables, and I'm not so keen on doing it manually...

Error when creating a Table Partition

$
0
0

Hello Forum

We have several huge databases here so I've suggested that we introduce Table Partitioning to some of the Tables where these tables are holding the majority of the data

For the first set of Databases; I've come up with the approach of partitioning the data on have yearly chunks based on the "Date Scanned" field of the Table

The smallest date is circa February 2007; so I've generated 106 File Groups, 106 Files (1 file associated with each new File Group) and the Partition Function; all is fine up to this point.

The issue I am having is when I'm attempting to create the Partition Scheme, it is coming up with the error: -

Msg 7707, Level 16, State 1, Line 83

The associated partition function 'ufn_PartitionByDateScanned' generates more partitions than there are file groups mentioned in the scheme 'PartionDocumentsScheme'.

However I have compared the function and the script for the Partition Scheme and the both contain 106 Partitions/File Groups, I am even getting this error when I attempt to create the Function and Scheme with just six Partitions and File Groups

This is my function script: -

CREATEPARTITIONFUNCTION ufn_PartitionByDateScanned(date)as

RANGERIGHTFOR VALUES

(

'30-Jun-2007','31-Dec-2007','30-Jun-2008','31-Dec-2008','30-Jun-2009','31-Dec-2009',

'30-Jun-2010','31-Dec-2010','30-Jun-2011','31-Dec-2011','30-Jun-2012','31-Dec-2012','30-Jun-2013','31-Dec-2013','30-Jun-2014','31-Dec-2014','30-Jun-2015','31-Dec-2015','30-Jun-2016','31-Dec-2016','30-Jun-2017','31-Dec-2017','30-Jun-2018','31-Dec-2018','30-Jun-2019','31-Dec-2019',

'30-Jun-2020','31-Dec-2020','30-Jun-2021','31-Dec-2021','30-Jun-2022','31-Dec-2022','30-Jun-2023','31-Dec-2023','30-Jun-2024','31-Dec-2024','30-Jun-2025','31-Dec-2025','30-Jun-2026','31-Dec-2026','30-Jun-2027','31-Dec-2027','30-Jun-2028','31-Dec-2028','30-Jun-2029','31-Dec-2029',

'30-Jun-2030','31-Dec-2030','30-Jun-2031','31-Dec-2031','30-Jun-2032','31-Dec-2032','30-Jun-2033','31-Dec-2033','30-Jun-2034','31-Dec-2034','30-Jun-2035','31-Dec-2035','30-Jun-2036','31-Dec-2036','30-Jun-2037','31-Dec-2037','30-Jun-2038','31-Dec-2038','30-Jun-2039','31-Dec-2039',

'30-Jun-2040','31-Dec-2040','30-Jun-2041','31-Dec-2041','30-Jun-2042','31-Dec-2042','30-Jun-2043','31-Dec-2043','30-Jun-2044','31-Dec-2044','30-Jun-2045','31-Dec-2045','30-Jun-2046','31-Dec-2046','30-Jun-2047','31-Dec-2047','30-Jun-2048','31-Dec-2048','30-Jun-2049','31-Dec-2049',

'30-Jun-2050','31-Dec-2050','30-Jun-2051','31-Dec-2051','30-Jun-2052','31-Dec-2052','30-Jun-2053','31-Dec-2053','30-Jun-2054','31-Dec-2054','30-Jun-2055','31-Dec-2055','30-Jun-2056','31-Dec-2056','30-Jun-2057','31-Dec-2057','30-Jun-2058','31-Dec-2058','30-Jun-2059','31-Dec-2059'

)

GO

And this is my Partition Scheme Script: -

CREATEPARTITION SCHEME PartionDocumentsScheme ASPARTITION ufn_PartitionByDateScanned TO

(

[Grp_2007Part01],[Grp_2007Part02],[Grp_2008Part01],[Grp_2008Part02],[Grp_2009Part01],[Grp_2009Part02],

[Grp_2010Part01],[Grp_2010Part02],[Grp_2011Part01],[Grp_2011Part02],[Grp_2012Part01],[Grp_2012Part02],[Grp_2013Part01],[Grp_2013Part02],[Grp_2014Part01],[Grp_2014Part02],[Grp_2015Part01],[Grp_2015Part02],[Grp_2016Part01],[Grp_2016Part02],[Grp_2017Part01],[Grp_2017Part02],[Grp_2018Part01],[Grp_2018Part02],[Grp_2019Part01],[Grp_2019Part02],

[Grp_2020Part01],[Grp_2020Part02],[Grp_2021Part01],[Grp_2021Part02],[Grp_2022Part01],[Grp_2022Part02],[Grp_2023Part01],[Grp_2023Part02],[Grp_2024Part01],[Grp_2024Part02],[Grp_2025Part01],[Grp_2025Part02],[Grp_2026Part01],[Grp_2026Part02],[Grp_2027Part01],[Grp_2027Part02],[Grp_2028Part01],[Grp_2028Part02],[Grp_2029Part01],[Grp_2029Part02],

[Grp_2030Part01],[Grp_2030Part02],[Grp_2031Part01],[Grp_2031Part02],[Grp_2032Part01],[Grp_2032Part02],[Grp_2033Part01],[Grp_2033Part02],[Grp_2034Part01],[Grp_2034Part02],[Grp_2035Part01],[Grp_2035Part02],[Grp_2036Part01],[Grp_2036Part02],[Grp_2037Part01],[Grp_2037Part02],[Grp_2038Part01],[Grp_2038Part02],[Grp_2039Part01],[Grp_2039Part02],

[Grp_2040Part01],[Grp_2040Part02],[Grp_2041Part01],[Grp_2041Part02],[Grp_2042Part01],[Grp_2042Part02],[Grp_2043Part01],[Grp_2043Part02],[Grp_2044Part01],[Grp_2044Part02],[Grp_2045Part01],[Grp_2045Part02],[Grp_2046Part01],[Grp_2046Part02],[Grp_2047Part01],[Grp_2047Part02],[Grp_2048Part01],[Grp_2048Part02],[Grp_2049Part01],[Grp_2049Part02],

[Grp_2050Part01],[Grp_2050Part02],[Grp_2051Part01],[Grp_2051Part02],[Grp_2052Part01],[Grp_2052Part02],[Grp_2053Part01],[Grp_2053Part02],[Grp_2054Part01],[Grp_2054Part02],[Grp_2055Part01],[Grp_2055Part02],[Grp_2056Part01],[Grp_2056Part02],[Grp_2057Part01],[Grp_2057Part02],[Grp_2058Part01],[Grp_2058Part02],[Grp_2059Part01],[Grp_2059Part02]

)


Please click "Mark As Answer" if my post helped. Tony C.

ORA-01403: no data found (Sub Query With a Where Clause)

$
0
0

I am using a linked server to Oracle 11g through OraOLEDB 11.2.0.3.20 64-bit client. The previous query worked on MSDAORA and sort of works on the OraOLEDB.

WORKS

IF 'X' IN (SELECT SOMEFIELD FROM SOMEVIEW) BEGIN
    PRINT 'Success'
END
DOES NOT WORK

IF 'X' IN (SELECT SOMEFIELD FROM SOMEVIEW WHERE ANOTHERFIELD = 2) BEGIN
    PRINT 'Success'
END


The sub query by itself with the WHERE clause works fine.  The error message I get is:

OLE DB provider "OraOLEDB.Oracle" for linked server "LIOS" returned message "ORA-01403: no data found".
Msg 7346, Level 16, State 2, Line 1
Cannot get the data of the row from the OLE DB provider "OraOLEDB.Oracle" for linked server "LIOS". 

The view is what contains the linked server.

Any ideas?

Dynamic Queries Using Temp Tables

$
0
0

Greetings August Members -

A couple of days ago, I had a question on how to use a variable in a FROM statement. The answer was to convert the query to a string, modify the FROM statement as needed, populate a variable (@Variable) and use EXEC (@Variable) to run the query.

Worked like a champ.

But, I need this to populate a temp table. Unfortunately, although it works gangbusters when just retrieving data for display, when I add the INTO #Temp_Table, all it does is return an empty table.

Following is the code;

---------------------------------------------
/*
	If #Temp_Table exists, drop it.
*/
IF OBJECT_ID('tempdb.dbo.#Temp_Table') IS NOT NULL
	DROP TABLE #Temp_Table;
---------------------------------------------
/*
	Set the relevant period.
*/
DECLARE @Period AS varchar(6)
	SET @Period = '201611'
PRINT @Period;
---------------------------------------------
/*
	Create the temp table, #Temp_Table.
*/
CREATE TABLE #Temp_Table
	(
	Eff_Month varchar(6) NULL,
	X nvarchar(255) NULL,
	Y nvarchar(255) NULL,
	Z nvarchar(255) NULL
	)
---------------------------------------------
/*
	Create a dynamic query with the updated period (@Period) to populate the
	temp table, #Temp_Table.
*/
DECLARE @SQL AS varchar(MAX)
	SET @SQL =
	'SELECT DISTINCT
		@Period AS Eff_Month,
		X,
		Y,
		Z
	INTO
		#Temp_Table
	FROM
		MBRS_@Period;'

SELECT @SQL=REPLACE(@SQL, '@Period', @Period)
PRINT @SQL;

EXEC (@SQL);
---------------------------------------------
SELECT DISTINCT
	Eff_Month,
	X,
	Y,
	Z
FROM
	#Temp_Table;
---------------------------------------------

And, I get nuthin'.

But, leave off the INTO #Temp_Table, and it works fine.

Is the INTO statement not allowed when using EXEC? Or, is it just that temp tables aren't allowed?

Oh, just to cover all the bases, if I don't use the EXEC command, and just run this as a straight query with the INTO, it also works fine. I'm just trying to streamline things so that I don't have to go through the hassle of modifying month parameters when we receive this monthly report. Originally, it was a one-shot, so hard-coding wasn't an issue, but now it's been decided this is to be a monthly thing, and I'm trying to minimize the conversion process.

Thanx!


Querying JSON Text using OPENJSON

$
0
0

SELECT A.*, (Coalesce(who0,0) + .......+ Coalesce(who200,0)) As TotalEffort

FROM 

Table A 

CROSS APPLY 

OPENJSON(A.Col1, '$.SomeNode') --- (Assume Col1 is the JSON Field with NVARCHAR(MAX) )

WITH 

(SomeId INT '$.SomeId', 

[who0] FLOAT '$.WeekHours[0]',

[who1] float '$.WeekHours[1]', 

.

..

...

[who200] float '$.WeekHours[200]'

) j

The [weekhours] element is dynamic - it could be 20, 40, upto 200. So I need to sum them up to get aggregate.

Now the query performs quite well if I define 150 week hour columns of the Json (openJson) , it takes 2-3 seconds to return result.

Anything higher than 152 weekhour columns, it takes more than 2 minutes to execute

Why would adding just 2 additional columns hamper performance so much ?

Eventually I want to be able to provide all 200 week hour columns in the OpenJson.




invoking a sql server procedure over a db link from oracle

$
0
0
How to  invoke a sql server procedure over a db link from oracle?

Prashanth

Add Column that is the Concat of two existing columns

$
0
0

I have two columns:

ClientFirstName

ClientLastName

in the existing table:

tblClient

I want to add a column:

ClientLetter

and have that column be a concatenation of the two previously mentioned columns. 

I tried the following query with no success:

ALTER TABLE tblClient
ADD ClientLetter nvarchar(255) NOT NULL  
DEFAULT ClientFirstName + ' ' + ClientLastName WITH VALUES 

There were a number of errors returned, suggesting in summary that I did not know what I was doing. 

How do I get this extra column added?

Thanx

Update if null

$
0
0

Good day, 

I need to update columns only if they have nulls

I did it like this

DECLARE @t TABLE(ID INT,Nm varchar(100),gr INT,	rn INT)
DECLARE @p TABLE(ID INT,Nm varchar(100),gr INT,	rn INT)
INSERT @t VALUES (1,NULL,1,1),(2,null,1,2),(3,'vv',2,1),(4,'v22v',2,2),(5,'v22v',1,3)
INSERT @p VALUES (1,NULL,1,1),(2,null,1,2),(3,'vv',2,1),(4,'v22v',2,2),(5,'v22v',1,3)

SELECT
	Nm = COALESCE(t.Nm,d.Nm),*
FROM @t t
 INNER JOIN @p d on t.gr = d.gr and  d.rn > 1
WHERE t.ID = 1

UPDATE t
SET
	Nm = COALESCE(t.Nm,d.Nm)
FROM @t t
 INNER JOIN @p d on t.ID = d.gr and  d.rn > 1
WHERE t.ID = 1

SELECT * FROM @t t
WHERE t.ID = 1

gr - is group determine that object is the same

But if i change scenario to this one 

DECLARE @t1 TABLE(ID INT,Nm varchar(100))
DECLARE @p1 TABLE(ID INT,gr INT,rn INT)
INSERT @t1 VALUES (1,NULL),(2,null),(3,'vv'),(4,'v22v'),(5,'v22v')
INSERT @p1 VALUES (1,1,1),(2,1,2),(3,2,1),(4,2,2),(5,1,3)

SELECT
	coalesce(t.Nm,f.name),*
FROM @t1 t
INNER JOIN @p1 d on t.ID = d.ID and d.rn = 1
INNER JOIN (
	SELECT a.id,a.Nm as Name,b.gr FROM @t1 a
		INNER JOIN @p1 b on a.ID = b.ID and b.rn > 1
) f on d.gr = f.gr
WHERE t.ID = 1

UPDATE t
SET
	Nm = coalesce(t.Nm,f.name)
FROM @t1 t
INNER JOIN @p1 d on t.ID = d.ID and d.rn = 1
INNER JOIN (
	SELECT a.id,a.Nm as Name,b.gr FROM @t1 a
		INNER JOIN @p1 b on a.ID = b.ID and b.rn > 1
) f on d.gr = f.gr
WHERE t.ID = 1

SELECT * FROM @t1 t
WHERE t.ID = 1


Update doesn't work

Please give me suggestion how to solve this.




MS SQL

Return Statement

$
0
0

 


I am new to SQL Server. Please help me with this issue

RAISERROR('There is a problem in the code',16,1)RETURN-1

This is working perfectly fine. So I put this in a common procedure like this:

CREATEprocedure[dbo].[Raise_Error](@ErrorMsg varchar(6000),@ErrorSeverity integer =16,@ErrorState integer =1)ASBEGINRAISERROR(@ErrorMsg,@ErrorSeverity,@ErrorState)RETURN-1END

Now when I call this procedure from another procedure    

CREATEPROCEDURE TEST_ORIGASBEGINIFNOTEXISTS(SELECT*FROMtablewhere FISCALYEAR='2016')BEGINEXEC utils.dbo.[Raise_error]@ErrorMsg ='There are no valid records for     processing'RETURN-1END

I am getting an error message as "

Msg 178, Level 15, State 1, Line 23

A RETURN statement with a return value cannot be used in this context"

Could anyone throw some light on what is happening here ?I need to return -1 here .How is that possible ?

Thanks

Aparna

trigger on deletion

$
0
0

Hi experts,

 

This should be simple, but I am unable to code it or find an example.

 

 

I need to create a trigger for a deletion:

 

-the trigger should not prevent the deletion.

-the trigger should insert in another table 3 columns: getdate(), the name of the job/sp or user that deleted the record.

 

Nothing else. In short, I am just trying to find the person or maybe job, that is deleting a few records every month from one of my tables.

 

Thanks!

How to compare Image data type in SQL SERVER and BLOB in Oracle

$
0
0
Used HASHBYTES(MD5) Algorithm and compare but it is returning different value .

SQL Server: Hierarchical query with depth

$
0
0

i have to show employee and his manager name with depth.

if simon is top manager and katie's manager is simon and john's manager is katie then simon level would be 0 because he is top and katie level will be 1 and john level will be 2. i tried below way but not getting desired output. please tell me what to rectify in code.

my code

Declare@ID INT
SET @ID=6;

WITH EmployeeCTE AS(Select ID,Name,MgrID,0as level FROM Employee
    WHERE ID=@ID

    UNION ALL

    Select emp.ID,emp.Name,emp.MgrID, level+1as level FROM Employee emp
    JOIN EmployeeCTE on emp.ID =EmployeeCTE.MgrID)--select*fromEmployeeCTESelect e1.Name,ISNULL(e2.Name,'Top BOSS')as[ManagerName], e2.level fromEmployeeCTE e1 left join EmployeeCTE e2
on e1.MgrID=e2.ID

How to show Parent/Child hierarchy like tree view

$
0
0

I have a parents table looks like this

ID       | PARENT_ID | NAME
1        | Null      | Bill
2        | 1         | Jane
3        | 1         | Steve
4        | 2         | Ben
5        | 3         | Andrew

Id like to get a result set like this

Bill---Jane------Ben---Steve------Andrew
i found one sql to achieve the same similar effect but sql is bit hard there. so some one see the sql can tell me how to achieve same output with easy sql.

my sql as follows

declare @pc table(ID int, PARENT_ID int,[NAME] varchar(80));

insert into@pcselect1,NULL,'Bill'union allselect2,1,'Jane'union allselect3,1,'Steve'union allselect4,2,'Ben'union allselect5,3,'Andrew'union allselect6,NULL,'Tom'union allselect7,8,'Dick'union allselect8,6,'Harry'union allselect9,3,'Stu'union allselect10,7,'Joe';;with r as(select ID, PARENT_ID,[NAME], depth=0,sort=cast(ID as varchar(max))from@pcwhere PARENT_ID isnullunion allselect pc.ID, pc.PARENT_ID, pc.[NAME], depth=r.depth+1,sort=r.sort+cast(pc.ID as varchar(30))from r
      inner join @pc pc on r.ID=pc.PARENT_IDwhere r.depth<32767)--select*from Rselect tree=replicate(' ',r.depth*3)+r.[NAME]from r
order by sort
option(maxrecursion 32767);

output looks like

tree------------------BillJaneBenSteveAndrewStuTomHarryDickJoe

thanks

Populating Added Column

$
0
0

I've added a column to a table that already has about two thousand records. The column will contain whatever value is entered by the user into the interface, but it will usually be the first and last name together. I need a query to enter a value into for the records that already exist that contains the first and last name. From the on it will be a nvarchar(255) field that accepts the users input for that field.

Thanx for any help.

tod

Update each value

$
0
0

Hi,

 I've a table like below:

Employee

ID        Number

1           11

2           22

3           33

Now I need to update Number column values, set 11 to 100, 22 to 200 and 33 to 300. I know it can be done using multiple update statements but is it possible with one update statement?

TIA 

RTRIM/LTRIM is not working on a set of data

$
0
0

Hi,

I am working on PDW and recently one of my users reported that RTRIM is not working. When they try to extract data with below query, the data is coming without getting trimmed.  But when I try to perform RTRIM with text assigned to a string with trailing spaces.

By the way the column data type is varchar(55) 

select 

RTRIM(REPLACE(REPLACE(REPLACE(column,CHAR(10),''),CHAR(13),''),CHAR(9),''))

from <TableName>

where EffDate ='2016-11-17'

Need help in fixing this issue..

Thanks

Pradeep

Viewing all 23857 articles
Browse latest View live


Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>