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

Troubling query


Return values not seen in previous records

$
0
0

I'd like to be able to return Code values below that have not occurred previously (ordered by ID).  I have a feeling it's going to involve a ROW_NUMBER() and CTE, but I can't quite put my finger on it.  See the example below.

DROP TABLE #codes
CREATE TABLE #codes (ID INT NOT NULL,
				 Code VARCHAR(20) NOT NULL)

ALTER TABLE #codes
ADD CONSTRAINT pk_codes PRIMARY KEY (ID, Code)

INSERT INTO #codes (ID,
				Code)
VALUES
(1, 'A'),
(1, 'B'),
(1, 'C'),
(1, 'D'),
(1, 'F'),
(2, 'A'),
(2, 'B'),
(2, 'C'),
(2, 'D'),
(2, 'E'),-- not seen in #1 - return this record
(3, 'B'),
(3, 'C'),
(3, 'D'),
(3, 'E'),
(3, 'F'),-- not seen in #2 but was seen in #1 so no need to return this record
(3, 'G') -- not seen in #1 or #2 - return this record

SELECT *
  FROM #codes
  ORDER BY ID, Code

I need a query to return (2, 'E') and (3, 'G') because they did not occur in ID's prior to them.  Hope this makes sense.  Any help?

Thanks!

Distinct Cummulative count

$
0
0

I need to calculate the distinct Cummulative count for the incremental months

As shown below

Month PersonName
7 sam
7 kim
7 tim
8 sam
8 tom
8 rex
8 ram
9 sam
10 Rob

o/p :

Month CountPerMonth DistinctCummulativeCount
7 3  3
8 4  6
9 1  6
10 1  7

CountPerMonth=count for respective month

DistinctCummulativeCount=column should give distinct count for the months in (7),(7,8),(7,8,9), (7,8,9,10) respectively.

Appreciate your help..

Thanks.

Hi Experts

$
0
0

How to convert a number 41330 into dateformat yyyymmdd (20130311)??

Any insights would be helpful!

Syntax error declaring variables within trigger

$
0
0

I'm writing a trigger that when a new record is added to one database (basically a new customer being added), it then adds some of those details to a second database which is used by another internal system.

I've come up with the following code :

create trigger NewEntity
on [Intranet-Test].[dbo].[vpw_Entities]
after insert
as
	declare @type_id int
	declare @entity_id int
	declare @Is_Active bit
	declare @Entity_Name nvarchar(256)
	@Is_Active=inserted.IsActive
	@entity_id=inserted.EntityID
	@Entity_Name=inserted.EntityName
	@type_id=inserted.TypeID

	if @type_id in ('2','3')
	begin
		insert into [TimeTracking-Test].[dbo].[clients] (clientid, active, clientname)
		values (@entity_id, CAST(@Is_Active as INT), @Entity_Name)
	end
go

but within SSMS it's indicating a syntax error near the "@Is_Active=inserted.IsActive" line, which appears to be related to the declare statements (eg if I add anything between them the new line gets the syntax error).

Looking online I can't find any indication of why I'd be getting this error, though I'm assuming that variable declaration is actually allowed within a trigger.

Anyone know why this isn't working? If it is the declare statements at fault, do you have any ideas how to achieve the same thing without them? I tried putting the inserted.entityname etc references directly into the values part of the insert statement but that also gave me an error.

How to debug a stored procedure in sql server 2012 ?

$
0
0

whenever I do a change to a stored procedure and then run the alter proc again

after that I place a break point on the exec stored procedure and try to step into the code 

SQL management studio starts stepping into an older version of the stored procedure (i.e it does not feel the changes I made )

How to get it to step through the latest version ? 

How to use array list with fixed values to insert record in trigger

$
0
0

I have a list  of number 1,30,40,45,60 . These numbers are not being changed so I  don't need to keep in a table. So have to create a  after insert trigger   for 

As

Begin

@list =  1,30,40,45,60 // Array value 

for i=1 to @list.count

Insert into mappingtable(arrayvalue,itemcode) values (list[i],Inserted.Itemcode)

Next

End

Please can you help with a code 

Regards

Pol


polachan



complex query

$
0
0

I am trying to get following result set out of single column. In a column when it hit a particular value in columnA it will change column B value 

Table A

Column A

-----------------

111

AAA

BBB

CCC

AAA

222

XXX

AAA

DDD


Result

Column A      COLUMNB

AAA                111

BBB                111

CCC               111

AAA                111

 

XXX                 222

AAA                 222

DDD                222



Data Type

$
0
0

Hi all,

I've heard that you should not store dates ie "02/02/2014" as strings and they should be stored as datetime.

Can someone explain please? Would this cause me any issues, I don't see any.....

looking for CURSOR replacement, please suggest!

$
0
0

Hello Experts,

I having some master tables "#ACTION_MASTER" & "#RPT_MILE_MASTER" and a link table "#ACTION_MILE_RPT_LINK" showing their relationship.

And again I having a derive table "#TBL" to finally update the master table ''#ACTION_MASTER".

I am able to do the task with below approach and I would like to know how to optimize it, please suggest and let me know for any other information. Thanks! 

CREATE TABLE #ACTION_MASTER (UID INT, ACTION_ID INT, IS_ACTV BIT)
INSERT INTO #ACTION_MASTER VALUES (1, 102, 1), (2, 103, 1)
--SELECT * FROM #ACTION_MASTER

CREATE TABLE #RPT_MILE_MASTER (UID INT, RPT_ID INT, MILE_ID INT, MILE_STATUS INT)
INSERT INTO #RPT_MILE_MASTER VALUES (1, 12, 1, 5), (2, 13, 2, 2)
--SELECT * FROM #RPT_MILE_MASTER

CREATE TABLE #ACTION_MILE_RPT_LINK (LINK_ID INT, ACTION_ID INT, RPT_ID INT, MILE_ID INT)
INSERT INTO #ACTION_MILE_RPT_LINK VALUES (1, 102, 12, 1), (2, 102, 13, 2), (3, 103, 13, 2)
--SELECT * FROM #ACTION_MILE_RPT_LINK

CREATE TABLE #TBL (RPT_ID INT, MILE_ID INT, MILE_STATUS INT)
INSERT INTO #TBL VALUES (13, 1, 5), (13, 2, 5)
--SELECT * FROM #TBL


DECLARE @ACTION_ID INT
DECLARE DB_CURSOR CURSOR FOR  

SELECT DISTINCT ACTION_ID FROM #ACTION_MILE_RPT_LINK WHERE MILE_ID IN (SELECT MILE_ID FROM #TBL WHERE MILE_STATUS = 5)  

OPEN DB_CURSOR   
FETCH NEXT FROM DB_CURSOR INTO @ACTION_ID
WHILE @@FETCH_STATUS = 0   
BEGIN   
	   IF EXISTS(
	   SELECT * FROM #ACTION_MILE_RPT_LINK
	   WHERE MILE_ID IN (SELECT MILE_ID FROM #TBL WHERE MILE_STATUS = 5) 
	   AND RPT_ID NOT IN (SELECT DISTINCT RPT_ID FROM #TBL)
	   AND ACTION_ID = @ACTION_ID)
	   BEGIN
	    DECLARE @COMPARE TABLE (RPT_ID INT, MILE_ID INT, MILE_STATUS INT)
		INSERT INTO @COMPARE
			SELECT RPT_ID, MILE_ID, 5 'MILE_STATUS' FROM #ACTION_MILE_RPT_LINK
			WHERE MILE_ID IN (SELECT MILE_ID FROM #TBL WHERE MILE_STATUS = 5) 
			AND RPT_ID NOT IN (SELECT DISTINCT RPT_ID FROM #TBL)
			AND ACTION_ID = @ACTION_ID
		IF NOT EXISTS(
        SELECT RPT_ID, MILE_ID, MILE_STATUS FROM #RPT_MILE_MASTER WHERE RPT_ID IN (SELECT RPT_ID FROM @COMPARE)
		EXCEPT
		SELECT RPT_ID, MILE_ID, MILE_STATUS FROM @COMPARE)
		BEGIN
			UPDATE #ACTION_MASTER SET IS_ACTV = 0 WHERE ACTION_ID = @ACTION_ID
		END
	   END
	   ELSE
	   BEGIN
		UPDATE #ACTION_MASTER SET IS_ACTV = 0 WHERE ACTION_ID = @ACTION_ID
	   END

       FETCH NEXT FROM DB_CURSOR INTO @ACTION_ID
END   
CLOSE DB_CURSOR   
DEALLOCATE DB_CURSOR
--SELECT * FROM #ACTION_MASTER
DROP TABLE #ACTION_MASTER
DROP TABLE #RPT_MILE_MASTER
DROP TABLE #ACTION_MILE_RPT_LINK
DROP TABLE #TBL

Update one table based on condition from another table using date ranges

$
0
0

Hello!

I have two tables:

DateRange (consists of ranges of dates):

StartDate            FinishDate        Condition

2014-01-02       2014-01-03           true

2014-01-03      2014-01-13          false

2014-01-13      2014-01-14           true

Calendar (consists of three-year dates):

CalendarDate    IsParental

2014-01-01

2014-01-02

2014-01-03

2014-01-04

2014-01-05

2014-01-06

2014-01-07

2014-01-08

2014-01-09

2014-01-10

...

I want to update table Calendar by setting  IsParental=1  for those dates that are contained in table DateRange betweenStartDate and FinishDate AND Condition IS TRUE.

The query without loop should look similar to this but it works wrong:

UPDATECalendar

  SET IsParental = 1

 WHERECalendarDate   BETWEEN(SELECTStartDate 

                                                                 FROM  DateRange

                                                                 WHERE Calendar.  CalendarDate   = DateRange. StartDate)

                   AND   (SELECT StartDate 

                                                                 FROM  DateRange

                                                                 WHERE Calendar.  CalendarDate   = DateRange. FinishDate   )

        ANDCondition  IS TRUE

;

Is it possible to do without loop? Thank you for help!

Anastasia

updating result set in a single statement

$
0
0

Hello All,

Is it possible to update a result set in a single query?

 UPDATE (SELECT * FROM [TestEnvironment].[dbo].[Table_1]) as a
 SET a.col1 = 'abcd' WHERE a.col2=1



Thanks and Regards, Readers please vote for my posts if the questions i asked are helpful.

split a string using SQL

$
0
0

possible to split a string according to comma and separate in a variable. For example: @string = '11111,22222,33333',

and put them in 3 variables

TSQL Geography STGeomFromText Displaying Wrong Result

$
0
0
I'm trying to write a code which will tell me whether point is inside polygon or not
DECLARE @Latitude varchar(20) = '41.694110'
DECLARE @Longitude varchar(20) = '44.833680'
DECLARE @g geography;
DECLARE @p geography;

DECLARE @PolygonString varchar(500) = 'POLYGON((41.711921 44.658505, 41.851703 44.773175, 41.763158 44.972302, 41.654421 44.843083, 41.711921 44.658505))'

SET @g = geography::STGeomFromText(@PolygonString, 4326);
SET @p = geography::Point(@Latitude, @Longitude, 4326)

SELECT @g.STIntersects(@p)

It always return 0. Here is visual representation of scenario.

http://sbtutor.com/

Any ideas what is wrong with my code?

Thanks.


Please Mark as Answer and Vote as Helpful if I helped.

Also please visit my blog http://msguy.net/

Partitioning Advice on PRIMARY FILE GROUP

$
0
0

Hi,

I wonder if you can help. I would like some advice on partitioning within the PRIMARY file group. Basically I have a lot of experience on partitioning and in the past I have followed best practice is documents such asPartitioned Table and Index Strategies Using SQL Server 2008   and the Analysis Services Performance Guide   so in summary when partitioning in the past I have followed best practice, e.g. have one file group per partition and have your partition key as a component within the primary key of the table you are partitioning.

However following best practice in this way can require a lot of maintainence, and the system I am performance tuning at the moment has a limited life span.

So in this context I wonder if there are any advantages of basing partitioning on a PRIMARY file group?

Kind Regards,

Kieran.


Kieran Patrick Wood http://www.innovativebusinessintelligence.com http://uk.linkedin.com/in/kieranpatrickwood http://kieranwood.wordpress.com/


Left Outer Join on same table clarification

$
0
0

HI,

I have a table that gets populated from 3<sup>rd</sup> party system. We don’t have control over it. So, the table has master record (master) and children. Master type is 78 and children’s type is 64. So, it looks like this. In the 3<sup>rd</sup> party system, if Master transaction gets cancelled, it is recorded as type 178. If child is cancelled, then it is 164. Once the child is cancelled and created again using one process then newly created transaction will have 65 as type. Same thing with Master cancelled transaction also. It will be 79. So, to summarize:

Master:                                                                                                                                                                      

Brand New Transaction type = 78

Cancelled Transaction type = 178

Cancelled with creation transaction type = 79

Child:

Brand New Transaction type = 64

Cancelled Transaction type = 164

Cancelled with creation transaction type = 65

I don’t have to bother about master records. I need to focus on only children for my query.

ID

TxnID

Master

Type

TDate

Location

193075

211554

211543

64

20140805

ABC

193076

211555

211543

64

20140805

NBC

193077

211556

211543

64

20140805

ABC

193080

211559

211558

64

20140805

ABC

193081

211562

211561

64

20140805

ABC

193082

211565

211564

64

20140805

CBC

193083

211565

211564

164

20140805

CBC

193084

211566

211564

65

20140805

AZC

--droptable#Transactions

CREATETABLE#Transactions

(

IDint,

TxnIDint,

mstTicketint,

Typecodeint,

Tdatedatetime,

Locationvarchar(10)

)

select*from #Transactions

Insertinto#Transactions(ID,TxnID, mstTicket,Typecode,Tdate,Location)

Select 193075, 211554,211543,64,'2014-08-05','ABC'UNIONALL

Select 193076, 211555,211543, 64,'2014-08-05', 'NBC'UNIONALL

Select 193077, 211556, 211543, 64,'2014-08-05',                               'ABC'UNIONALL

Select 193080, 211559, 211558, 64,'2014-08-05',                               'ABC'UNIONALL

Select 193081, 211562, 211561, 64,'2014-08-05',                               'ABC'UNIONALL

Select 193082, 211565, 211564, 64,'2014-08-05',                               'CBC'UNIONALL

Select 193083, 211565, 211564, 164,'2014-08-05',                             'CBC'UNIONALL

Select 193084, 211566, 211564, 65,'2014-08-05',                               'AZC'

selectT.TxnID,T.TypeCode,T.Location,TL.TxnID

From#TransactionsT

    LeftOuterJOIN#TransactionsTLON TL.TxnID =T.TxnIDandTL.TypeCode= 164

selectT.TxnID,T.TypeCode,T.Location,TL.TxnID

From#TransactionsT

    LeftOuterJOIN#TransactionsTLON TL.TxnID =T.TxnIDandTL.TypeCode= 164

WhereT.typecodein(64, 65)

I need a clarification regarding left Outer Join. 

In the first left outer join query both 64 and 164 both have TL.TxnID populated. Why is that?. What I understand from

left outer join is that ‘Returns all the rows’ from left table and only matching data from right table.

Here, matching row from right table is 211565 and 164 record (id 193083). So, only it should have TxnID populated. But row 211565 and 64 has TL.txnID getting populated (ID 193082).

Why is it? Am I not understanding left out join properly?

Thanks,

Sum Value with different date

$
0
0

Hi,

DECLARE @FromDateDate = '2014-01-01'
DECLARE @ToDateDate = '2014-12-31'
DECLARE @PreFromDateDate = '2013-01-01'
DECLARE @PreToDateDate = '2013-12-31'

CREATE TABLE TXN (ID varchar(10),TxnDate Date,Amount decimal(18,3));
INSERT into TXN (ID,TxnDate,Amount) values (1001,'2013-02-21',1000)
INSERT into TXN (ID,TxnDate,Amount) values (1001,'2013-05-01',2000)
INSERT into TXN (ID,TxnDate,Amount) values (1001,'2014-01-25',500)
INSERT into TXN (ID,TxnDate,Amount) values (1001,'2014-01-25',100)

INSERT into TXN (ID,TxnDate,Amount) values (1002,'2013-01-20',3000)
INSERT into TXN (ID,TxnDate,Amount) values (1002,'2013-07-21',4000)
INSERT into TXN (ID,TxnDate,Amount) values (1002,'2014-01-25',100)
INSERT into TXN (ID,TxnDate,Amount) values (1002,'2014-01-25',200)

select ID, sum(Amount) ThisYear,0 as PreviousYear 
FROMTXN TM WHERE TM.TxnDate BETWEEN @FromDate AND @ToDate
GROUP BY    ID

DROP table TXN

The result data is  pasted below

i need to sum values between @PreFromDate and @PreToDate and populate in PreviousYear column. means need result like below image

Regards

Kasim

How to check if a file exists in a directory?

$
0
0

Sorry to bother everyone with something so simple.  I installed and ran the function from here.

http://www.tech-recipes.com/rx/30527/sql-server-how-to-check-if-a-file-exists-in-a-directory/

Just like in that example, I'm running this.

select dbo.fc_FileExists('C:\Users\Ryan\Desktop\Briefcase\Best Coffee Bars in NYC.doc');

I'm getting a o0, but I know it should be 1.  Maybe there is a security or permission issue here.  I'm not sure.  I know one thing for sure, that the file is in that place!! 

What am I missing?  What could I be doing wrong here? 


Knowledge is the only thing that I can give you, and still retain, and we are both better off for it.

How can i get the least date in a column with another column ?

$
0
0

Hi All,

we have a table like below.

IDDate
10017/14/2010
10018/20/2011
100110/2/2012
10026/23/2009
100210/14/2012
10039/16/2012
100310/19/2013

i want result like below.

IDDate
10017/14/2010
10026/23/2009
10039/16/2012

please any one help me to get this done. i have so many records in my table. the above one just example.

Thanks in Advance,


rup

deleteing tempdb files

$
0
0

I am trying to delete a couple of tempdb data files and get the below errors. There are currently 4 tempdb files. I want to delete 3 and just keep one but I have tried the SSMS and t-sql and neither will let me delete them. I try to

DBCC SHRINKFILE (N'tempdev3' , EMPTYFILE)

And they try

ALTER DATABASE [tempdb]  REMOVE FILE [tempdev3]

Drop failed for DataFile 'tempdev5'.  (Microsoft.SqlServer.Smo)

The file 'tempdev5' cannot be removed because it is not empty. (Microsoft SQL Server, Error: 5042)


Alan

Viewing all 12890 articles
Browse latest View live


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