Copy Subtree, Recursive Sproc With Cursor Doesn't Work

Sep 20, 2007

Hi all,

I have a parent-child table, and i want to copy subtrees of it, so for instance this would be the starting point:
(id, parentId, label)
0, null, World
1, 0, US
2, 1, NY
3, 0, UK
4, 3, London

now i want to copy object 3 (UK) and it's children, so i would get
0, null, World
1, 0, US
2, 1, NY
3, 0, UK
4, 3, London
5, 0, UK_copy
6, 5, London_copy


I have this sproc:



Code Snippet

alter proc CopyObject


(@ObjectId int,

@NewParentId int)

as


declare @NewId int,

@NewName varchar


select @NewId = max(Id) + 1 from Object

select @NewName = [Name] + 'copy' from [Object] where Id = @ObjectId


-- copy object

INSERT INTO [Object]


([Id]

,[Name]

,[ParentId]

select @NewId,


@NewName,

@NewParentId

from [Object]

where Id = @ObjectId


-- copy children and set their parent to the newly created object

declare c cursor fast_forward for


select Id

from [Object]

where ParentId = @ObjectId


declare @ChildId int


open c

fetch next from c into @ChildId


while @@fetch_status = 0

begin


exec CopyObject


@ObjectID = @ChildId,

@NewParentId = @NewId

fetch next from c into @ChildId

end

close c

deallocate c





But htis throws an error that the cursor already exists:

Msg 16915, Level 16, State 1, Procedure CopyObject, Line 66

A cursor with the name 'c' already exists.

Msg 16905, Level 16, State 1, Procedure CopyObject, Line 72

The cursor is already open.

I've tried to think of an approach without cursors, but i can't figure it out. Because on the first pass, the new parentId will be the same as the parentId of the object to be copied. But the copies of the children of this first original object should have the parentid set to id of the copied object, and so all the way down the tree.

Any ideas?

Thanks in advance,

Gert-Jan

View 3 Replies


ADVERTISEMENT

Recursive Cursor

Sep 23, 2004

Hi,

I have 2 tables

tblparent

parent_term_id term_id
-------------- -----------
1 2
2 3

tblname

id name
----- ------------------------------------------
1 My top parent node
2 My second node
3 my child node


If I do a search for say 'my child node' I need to display where 'my child node' is in relation to the hierarchy. i.e i need to show it's parent and if that has a parent I need to show its parent etc... and continue until there are no more parents left

So using the table details if i search for 'my child node'

I need to display this :
My top parent node -> My second node - > my child node

The id for 'My top parent node' doesn't exist in tblparent because it is the top parent

Can anybody help with doing this

Thanks in advance

View 7 Replies View Related

Transact SQL :: STATIC Defines A Cursor That Makes Temporary Copy Of Data To Be Used By Cursor

Aug 12, 2015

In MSDN file I read about static cursor

STATIC
Defines a cursor that makes a temporary copy of the data to be used by the cursor. All requests to the cursor are answered from this temporary table in
tempdb; therefore, modifications made to base tables are not reflected in the data returned by fetches made to this cursor, and this cursor does not allow modifications

It say's that modifications is not allowed in the static cursor. I have a  questions regarding that

Static Cursor
declare ll cursor global static
            for select  name, salary from ag
  open ll
             fetch from ll
 
              while @@FETCH_STATUS=0
               fetch from ll
                update ag set salary=200 where 1=1
 
   close ll
deallocate ll

In "AG" table, "SALARY" was 100 for all the entries. When I run the Cursor, it showed the salary value as "100" correctly.After the cursor was closed, I run the query select * from AG.But the result had updated to salary 200 as given in the cursor. file says  modifications is not allowed in the static cursor.But I am able to update the data using static cursor.

View 3 Replies View Related

Logic Problem In Cursor/SPROC

Jul 23, 2005

SQL Server 2000I have a stored procedure that uses an extended SPROC to send an emailnotification to my customers when a document is distributed.However, the SPROC has an unexpected side effect.If I run it in its current incarnation, it only sends one email andthen exits. However, if I remove or comment out the block/* Set Job to processed */UPDATEtblJobsSETfldEmailProcessed = 1WHERE(fldJobID = @JobID)then it runs through the whole list as anticipated. Conceptually, itseems that the records in the cursor are changed if the underlyingtable is updated.Here is pseudo-code for what the SPROC does - whole SPROC below (withpart of the "WHERE" clause removed for readability). I haven'tincluded any table schemae but I don't think they're relevant.1. Open a cursor and fetch a list of all companies that need emailnotification for pending jobs.2. While records in the cursor...a) Format and send email from the cursorb) Write a record to the audit tablec) Update the jobs table for the current record3) Fetch next from cursorThere is an update trigger on the tblJobs table thus:CREATE TRIGGER "tblJobs_UTrig" ON dbo.tblJobs FOR UPDATE ASSET NOCOUNT ON/* * PREVENT UPDATES IF NO MATCHING KEY IN 'tblDistributionMaster' */IF UPDATE(fldDistributionID)BEGINIF (SELECT COUNT(*) FROM inserted) !=(SELECT COUNT(*) FROM tblDistributionMaster, inserted WHERE(tblDistributionMaster.fldDistributionID = inserted.fldDistributionID))BEGINRAISERROR 44446 'The record can''t be added or changed.Referential integrity rules require a related record in table''tblDistributionMaster''.'ROLLBACK TRANSACTIONENDEND/* * PREVENT UPDATES IF DEPENDENT RECORDS IN 'tblPrinterJobs' */IF UPDATE(fldJobID)BEGINIF (SELECT COUNT(*) FROM deleted, tblPrinterJobs WHERE(deleted.fldJobID = tblPrinterJobs.fldJobID)) > 0BEGINRAISERROR 44446 'The record can''t be deleted orchanged. Since related records exist in table ''tblPrinterJobs'',referential integrity rules would be violated.'ROLLBACK TRANSACTIONENDENDI can't see that this is relevant - I think it's something to do withwhere I'm updating the fldEmailProcessed field, but I need to do thishere, as outside the loop the fldJobID might be lost.Sorry it's all such a mess. Hope someone can help!ThanksEdward/*Checks all Jobs that were set to Despatched more than 24 hours ago,selects those that the companies elected to get email notification, andsends them emails.*/CREATE PROCEDURE stpSendEmailNotificationASDECLARE @rc intDECLARE @JobID intDECLARE @CompanyID intDECLARE @DocumentNumber varchar(50)DECLARE @Email varchar(50)DECLARE @DocumentURL varchar(750)DECLARE @Dat varchar(20)DECLARE @Subject varchar(100)SET @Dat = LEFT((CONVERT(varchar, GETDATE(), 100)), 11)DECLARE MailList CURSOR FORSELECTtblJobs.fldJobID,tblJobs.fldDocumentNumber,tblCompany.fldEmail,tblCompany.fldCompanyID,tblJobHistory.fldDocumentURLFROMtblJobHistory INNER JOINtblJobs ON tblJobHistory.fldJobID = tblJobs.fldJobIDINNER JOINtblDistributionMaster ON tblJobHistory.fldDistributionID =tblDistributionMaster.fldDistributionID INNER JOINtblCompany ON tblJobHistory.fldCompanyID =tblCompany.fldCompanyIDWHERE(tblJobs.fldEmailProcessed = 0)OPEN MailListFETCH NEXT FROM MailList INTO@JobID,@DocumentNumber,@Email,@CompanyID,@DocumentURLWHILE @@FETCH_STATUS = 0BEGIN/* Format and send the email to the customer here */SET @Subject = N'Document Distribution No: ' + @DocumentNumber +N' - Date: ' + @Datexec @rc = master.dbo.xp_smtp_sendmail@FROM = N'techlib@myco.co.uk',@FROM_NAME = N'Edward Collier',@replyto = N'techlib@myco.co.uk',@TO = @Email,@CC = N'',@BCC = N'',@priority = N'NORMAL',@subject = @Subject,@type = N'text/plain',@message = @DocumentURL,@messagefile = N'',@attachment = N'',@attachments = N'',@codepage = 0,@server = N'12.34.5.67',@timeout = 10000select RC = @rc/* Write result to audit table */INSERT INTO tblEmailAudit(fldRCNo,fldEmail,fldDocumentNumber,fldDate,fldCompanyID)VALUES(@rc,@Email,@DocumentNumber,GETDATE(),@CompanyID)/* Set Job to processed */UPDATEtblJobsSETfldEmailProcessed = 1WHERE(fldJobID = @JobID)FETCH NEXT FROM MailList INTO@JobID,@DocumentNumber,@Email,@CompanyID,@DocumentURLENDCLOSE MailListDEALLOCATE MailListGO

View 1 Replies View Related

Create A Cursor Inside A Sproc

May 16, 2008

I try to create a Sproc which will use a cursor to retrieve a few rows from a table. But the cursor part has given me problem. Here it is:


StudentInfo
StudentID StudentName DeptID
101 John 10
102 Alex 10
103 Beth 20
ClassInfo
ClassID DeptID
901 10
902 10
225 20
I want to create a Sproc which will retreive the student's classes in DeptID 10

Following is the Sproc and cursor:

use master
go
Create PROCEDURE [dbo].[getEnclishClasses]
@StudentID int
AS
Declare @printInsertStatement nvarchar(100)
ECLARE NewRowID int

Declare classCursor CURSOR FOR
SELECT ClassID, DeptID FROM [myTest].dbo.ClassInfo
WHERE DeptID=(SELECT DeptID FROM [myTest].dbo.StudentInfo
WHERE StudentID=@StudentID)

DECLARE @ClassID INT
DECLARE @DeptID INT

OPEN classCursor
FETCH NEXT FROM classCURSOR INTO
@ClassID, @DeptID
WHILE (@@FETCH_STATUs=0)
BEGIN
PRINT 'SET @newID = Scope_Identity()'
SET @printInsertStatement=
(Select 'INSERT INTO [myTest].dbo.ClassInfo (ClassID, DeptID) Values('
+CONVERT(NVARCHAR (10), @ClassID) + ','
+CONVERT(NVARCHAR (2), @DeptID)+')'
FROM [myTest].dbo.StudentInfo
WHERE DeptID=(SELECT DeptID FROM [myTest].dbo.StudentInfo
WHERE StudentID=@StudentID))

PRINT @printInsertStatement
END
CLOSE classCursor
DEALLOCATE classCursor
EXEC getEnclishClasses 101

Here is what I try to get (text with actual data from the table):
SET @newRowID = Scope_Identity()
INSERT INTO [myTest].dbo.ClassInfo VALUES(901, 10)
SET @newRowID = Scope_Identity()
INSERT INTO [myTest].dbo.ClassInfo VALUES(902, 10)

Here is what I had got (returning multiple lines, more than number of records I have):
Msg 512, Level 16, State 1, Procedure getEnclishClasses, Line 19
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

Thanks in advance for your help! Or is it a better way (not using a cursor). Each table has over 5,000 records.

View 8 Replies View Related

T-SQL (SS2K8) :: Replace Cursor - Convert To Recursive CTE Or While Loop

Jul 2, 2014

Need getting the below Cursor query convert to a Recursive CTE or with a while loop as I do not want to use a cursor.

Declare @Companyname Nvarchar (400)
declare @str nvarchar(MAX)
TRUNCATE TABLE STAGING.dbo.[IT_G_L Entry]
DECLARE GLEntry_cursor CURSOR FOR
SELECT REPLACE Name FROM Company where Name <> 'AAAAA'
OPEN GlEntry_cursor

[Code] ....

View 9 Replies View Related

T-SQL (SS2K8) :: Convert Cursor To Recursive CTE Or A Normal Query?

Sep 25, 2015

I have a stored proc I want to convert it to either a Normal Query using A while loop or a set based operation/recursive cte as I want to run it for multiple CompanyNames. I get the error message as An INSERT EXEC statement cannot be nested when I execute if for Multiple Companies using another Cursor

If I convert it to a Function I get the below error message

Invalid use of a side-effecting operator 'EXECUTE STRING' within a function

converting this query to a normal query or let me know if there is any change which need to done to work with multiple companynames.

CREATE PROC [dbo].[USPT] @CompanyName varchar(50),@tablename varchar(50)
AS
BEGIN
-- EXEC [USPT] 'xyz corp','Sales Header'
DECLARE @str1 VARCHAR (MAX)
set @str1 = '
DECLARE @No VARCHAR (MAX)

[code]....

View 5 Replies View Related

Can't Get SProc To Work

Aug 16, 2005

HiI can't seem to get this procedure to work correctly. Here's my code:DECLARE @PropertyDetails nvarchar (6)Select @PropertyDescription = PropertyDescription from Property whereApplicationID = @applicationidIf @PropertyDescription is not null or @PropertyDescription <> ''BeginIf (select isnumeric(PropertyDescription) from Property where ApplicationID =@applicationid) = 1INSERT INTO #errors VALUES (1410,@ApplicationID, 0, 'Y')ELSEINSERT INTO #errors values (1410, @ApplicationID, 0, 'N')EndI am trying to bring up an error advising users not to capture alphabets in afield called Property Description.I need to bring up the error from the #ERRORS table with the rule number 1410.My Syntax checks successful, but my error does not come up for the users. AmI missing something?Thanks for any help at all, guys.Driesen Pillay--Message posted via SQLMonster.comhttp://www.sqlmonster.com/Uwe/Forum...eneral/200508/1

View 5 Replies View Related

Transact SQL :: Recursive CTE Work Flow

May 7, 2015

how recursive CTE works...Synthesise table with non-recursive CTE

;WITH Employee (ID, Name, MgrID) AS
(
SELECT 1, 'Keith', NULL UNION ALL
SELECT 2, 'Josh', 1 UNION ALL
SELECT 3, 'Robin', 1 UNION ALL
SELECT 4, 'Raja', 2 UNION ALL

[code]....

the first part query will return one row
IDNameMgrIDnLevelFamily
1KeithNULL11

then this result set using after union all query .how the level + 1 condition is working ?  and how its return values .

View 7 Replies View Related

Cursor In Sproc To Kill Spids Loops Forever

Mar 20, 2000

I need a stored proc to kill spids, but the following sproc loops infinitely with the same [correct] spid being printed out. What am I doing wrong?

The select statement, when I execute it via the query grid, returns the correct and finite number of spids.

Any help greatly appreciated.
Judith


CREATE PROCEDURE rasp_KillDBProcess
@dbname varchar(128)
AS
declare @KillSpid smallint
declare @SQL varchar(1000)
--
declare DBCursor cursor Forward_only for SELECT distinct l.spid
FROM master.dbo.syslocks l INNER JOIN
master.dbo.sysdatabases d ON l.dbid = d.dbid
WHERE (d.name = N'coj_pcisdata')
open DBCursor
--
Fetch next from DBCursor into @Killspid
--
While (@@Fetch_status <> -1)
Begin
If (@@Fetch_status <> -2)
begin
print 'spid = ' + cast(@killspid as varchar(12))
--exec ('kill ' + @killspid)

end
--
end
Fetch next from DBCursor into @Killspid
--
close dbcursor
deallocate dbcursor
print 'end'

return

View 1 Replies View Related

Cannot Get My TREE VIEW Recursive Query To Work

Mar 17, 2007

My Table Structure

Category_ID Number
Parent_ID Number <----Category_ID reports to this colum
Category_Name Varchar....

MY QUERY <---I replaced the query above with my data
=============================
WITH Hierarchy(Category_ID, Category_Name, Parent_ID, HLevel)
AS
(
SELECT Category_ID, Category_Name, Parent_ID, 0 as HLevel FROM Dir_Categories
UNION ALL
SELECT SubCategory.Category_ID
, SubCategory.Category_Name,
SubCategory.Parent_ID,
HLevel + 1
FROM Dir_Categories SubCategory
INNER JOIN Hierarchy ParentCategory
ON SubCategory.Parent_ID = ParentCategory.Category_ID )
SELECT Category_ID,
Category_Name = Replicate('__', HLevel) + Category_Name,
Parent_ID,
HLevel
FROM Hierarchy

My OUTPUT============

All the categories under reporting to Parent_ID 0 or continuous, then the ones reporting to 1 and so fourth. Subcategories are not showing within their main categories. I AM GOING NUTS WITH THIS.

Can you help me please?

View 12 Replies View Related

Copy Result Set To Another Server From Within A Sproc?

Jun 4, 2007

I've got a stored procedure that selects some rows. These rows need to be placed in a table on another SQL Server.



Currently, I'm using some C#/ADO.NET code to execute the stored procedure, grab the results, connect up to the other server, and dump them there.



Is there a way that I can cut my little program out of the picture? Could I somehow copy the selected rows and insert them into the appropriate table on the other server, from within this stored procedure? I suspect this is way outside the scope of T-SQL (and hence my little program), no?

View 3 Replies View Related

After SP4, Proc W. Cursor Doesn't Release Keylocks

Aug 15, 2006

Existing Stored Procedure, has been running well on SQL since 7.0.(but needed some tweaking to migrate to 2000).Now all of a sudden after installing SP4 of SQL 2000,this process slows down, and SQL Spotlight shows the number of locksjust climbing throughout the processing run.According to the MS Knowledge Base Articles on KeyLocks .. this was aproblem that was *fixed* in the service pack ... where as for me it isnow broken.Article ID: 260652PRB: Nested Loop Join That Uses A "BOOKMARK LOOKUP ...WITH PREFETCH"May Hold Locks Longer http://support.microsoft.com/kb/260652/Article ID: 828096FIX: Key Locks Are Held Until the End of the Statement for Rows ThatDo Not Pass Filter Criteria http://support.microsoft.com/kb/828096/Anybody else have this issue, or have any "eazy" solutions?The proc cursors thru a list and runs a proc on each item in the "worklist".This is an existing systemwith no plans to turn the process into a set oriented one,as is going away shortly.

View 4 Replies View Related

DTS Doesn't Work Through Job

Sep 15, 2005

I'm pretty new to DTS, so forgive me if this is basic. I created a simple DTS package to run a query and export it to a text file. I can execute the package fine from my workstation through EM, but when I try to execute the job to run the package I get this error:
Error = -2147467259 (80004005) Error string: Error opening datafile: Access is denied.

I think that maybe SQL Agent doesn't have the right permissions to write to that network drive. What should the permissions be?

View 3 Replies View Related

IIF Doesn't Work

Nov 10, 2004

This is probably very simple, but I can't get passed this problem.

I have a report in MS Access that uses info generated by a query. One of the text fields in the query contains either the word 'Select' or the name of a course.
The report should display a space if the value is 'Select', or the actual value of the field in any other case. The field can never contain a null value.

I've used:
=IIf([optVoc1]="Select","",[optVoc1])
in the text box on the report, but this only returns #error regardless of the actual content of the field.

What am I doing wrong?

Regards,

BD

View 5 Replies View Related

Sql Job Doesn't Work

Aug 27, 2004

Hi all,

I create and schedule a SQL job to run every minute to update a table base on certain condition but it doesn't work. Job history says successful every time but the table doesn't get updated.

However if I move it to Query Analyzer and run it under dba, it will work. Thinking that it may have to do with the user the job run as, I then change run as user from self to dba. But still SQL job won't update my table.

Anything about user permission or security that I can check? Or it there any other possibility?

TIA

View 1 Replies View Related

Why Doesn't This Work

Apr 26, 2007

When I run the select its fine but I cannot delete..... i have done this many times and it has worked.... I cannot see the error what am i missing

select
eqnow.empnumber,
eqnow_names.empnumber,
eqnow_names.names
--delete
from
eqnow
inner join eqnow_names
on eqnow.empnumber = eqnow_names.empnumber
where
eqnow_names.names is null



i get this error
Server: Msg 156, Level 15, State 1, Line 4
Incorrect syntax near the keyword 'inner'.

View 3 Replies View Related

Doesn't Work

Oct 21, 2007



Msg 15123, Level 16, State 1, Procedure sp_configure, Line 78

The configuration option 'user instances enabled' does not exist, or it may be an advanced option.



Valid configuration options are

View 1 Replies View Related

Help! LIKE Doesn't Work!!!

Apr 19, 2008

Hi to all, I'm building (and learn) an application with VB Express. In "edit dataset with designer" I've build this sql query:

SELECT tbl_soggetto.[ID Soggetto], tbl_soggetto_tipo.Tipo, tbl_soggetto.[Cognome/Denominazione], tbl_soggetto.Nome, tbl_soggetto.Indirizzo, tbl_soggetto.CAP, tbl_soggetto.Città , tbl_soggetto.Provincia, tbl_soggetto.[Telefono 1], tbl_soggetto.[Telefono 2], tbl_soggetto.[Telefono 3], tbl_soggetto.[Telefono 4], tbl_soggetto.[eM@il 1], tbl_soggetto.[eM@il 2], tbl_soggetto.Note
FROM tbl_soggetto INNER JOIN tbl_soggetto_tipo ON tbl_soggetto.[ID Tipo] = tbl_soggetto_tipo.[ID Tipo]
WHERE (tbl_soggetto.[Cognome/Denominazione] LIKE '%' + @Testo + '%')


The LIKE doesn't work!
I call the query with Me.griglia.DataSource = Me.TA_tbl_soggetto_ricerca.Search_Cognome(Me.txt_trova.Text.Trim)

But with LIKE '%ABC%' work!

Me.griglia.DataSource = Me.TA_tbl_soggetto_ricerca.Search_Cognome()

Someone can help me? Thanks...

View 12 Replies View Related

SET Doesn't Work

Dec 11, 2006

When I try to install the problem I get the following error.

The SQL Server service failed to start. For more information, see the SQL Server Books Online topics, "How to: View SQL Server 2005 Setup Log Files" and "Starting SQL Server Manually."

The log tells me nothing useful. I can't start the thing manually because after clicking cancel on the error message, the installer proceeds to roll back the installation.

How do I fix this problem?








View 3 Replies View Related

Sum In Subquery Doesn't Work Well

Jun 8, 2005

This is the autogenerated code from the SelectCommand of my DataAdapter, except the red text. This DataAdapter is used to fill a DataGrid. What I want to do, is to calculate the total memory (4 slots) / PC.This code makes the sum of all memory of all PC's together.I'm not sure if the group by clause is needed here ...Me.OleDbSelectCommand1.CommandText = "SELECT PC.ID, PC.Nummer, PC.Netwerknaam, Case_Type.Type AS Case_Type, Processor_T" & _"ype.Type AS Processor_Type, Processor_Snelheid.Snelheid AS Processor_Snelheid, " & _"(SELECT SUM(Memory) FROM Memory, PC, RAM WHERE RAM.PcID = PC.ID AND RAM.GrootteID = Memory.ID)" & _"AS Memory, OS.Naam AS OS, OS_SP.Nummer AS OS_SP, Gebru" & _"iker.Naam AS Gebruiker_Naam, Status.Status, PC.Tagged FROM (Status RIGHT OUTER J" & _"OIN ((((((((PC LEFT OUTER JOIN (RAM LEFT OUTER JOIN Geheugen ON RAM.GrootteID = " & _"Geheugen.ID) ON PC.ID = RAM.PcID) LEFT OUTER JOIN Case_Type ON PC.Case_TypeID = " & _"Case_Type.ID) LEFT OUTER JOIN OS_SP ON PC.OS_SpID = OS_SP.ID) LEFT OUTER JOIN Ge" & _"bruiker ON PC.GebruikersID = Gebruiker.ID) LEFT OUTER JOIN Processor_Snelheid ON" & _" PC.Processor_SnelheidID = Processor_Snelheid.ID) LEFT OUTER JOIN Processor_Type" & _" ON PC.Processor_TypeID = Processor_Type.ID) LEFT OUTER JOIN OS ON PC.OsID = OS." & _"ID) LEFT OUTER JOIN Switchbox_Details ON PC.ID = Switchbox_Details.PcID) ON Stat" & _"us.ID = PC.StatusID) GROUP BY PC.ID, PC.Nummer, PC.Netwerknaam, Case_Type.Type, " & _"Processor_Type.Type, Processor_Snelheid.Snelheid, OS.Naam, OS_" & _"SP.Nummer, Gebruiker.Naam, Status.Status, PC.Tagged"I would like to know how to calculate the total memory for each separate PC.Hope you can help me.

View 5 Replies View Related

HELP! Sp_attach_db Doesn&#39;t Work!

Sep 20, 2000

I had a SQL Server falure. I rebiuld Master and tried to attach my database
with sp_attach_db? but get an error

Location: pageref.cpp:3931
Expression: rowLog.RowCount () == 1 || pPage->IsEmpty ()
SPID: 10
Process ID: 119

Connection Broken

View 1 Replies View Related

Attaching Db Doesn&#39;t Work

Mar 1, 2001

I try to copy a DB from one server to another. On the target server an older version of the DB has been deleted and I now try to attach the new version using "sp_attach_db DBname, Filelocation", but I always get an error "Device Activation error. The physical file name 'D:mssql7dataAgency_log.ldf' may be incorrect"
"Database 'Agency' cannot be Created"

To me it seems that the database is looking for the log files (now deleted).
I've tried forcing a new log file I created using the same locations for the mdfs. I've tried using create a new database and replace the mdf file, but nothing works.

View 3 Replies View Related

Trigger - This One Doesn't Work - Why?

Mar 31, 2003

Hi,

I wanted to create a new trigger, but Enterprise Manager tells me about an "Incorrect syntax near @UpdatedByID, line 28". I double-checked everything, but it still does not work :mad: .

Any hints :confused: ?

TIA,

-Gernot


Here is the statement (line 28 is marked with ***):


CREATE TRIGGER TransferToABII ON [dbo].[CALGeneral]
FOR INSERT
AS
BEGIN TRANSACTION
BEGIN
DECLARE @Event varchar(255),
@BBaseUID int,
@StartDate smalldatetime,
@EndDate smalldatetime,
@Details varchar(255),
@AddressID int,
@ProjectID int,
@UpdatedByID int,
@ActID int,
@EventID int

SELECT @Event = Event,
@BBaseUID = BBaseUID,
@StartDate = StartDate,
@EndDate = EndDate,
@Details = Details,
@AddressID = AddressID,
@UpdatedByID = UpdatedBy,
@ProjectID = ProjectID
FROM INSERTED

BEGIN
EXEC BrainBase.dbo.BB_NEW_CREATE_NoteTask_Ret *** (@UpdatedByID,
@AddressID,
@ProjectID,
@BBaseUID,
@StartDate,
GetDate(),
@Event,
NULL,
NULL,
NULL,
NULL,
@Details text,
@ActID = @ActID OUTPUT,
@EventID = @EventID OUTPUT)
END
BEGIN
UPDATE CALGeneral SET ActID = @ActID WHERE ID = INSERTED.ID
END
END

IF @@ERROR <> 0
BEGIN
RAISERROR('Error occured',16,1)
ROLLBACK TRANSACTION
END
COMMIT TRANSACTION

View 4 Replies View Related

Identity Doesn&#39;t Work

Nov 11, 1999

I'm working with mssql 6.5

I have an primary key column with Identity property.
And at the moment server doesn't insert the proper value to this column.

Error message is following

Msg 2601, Level 14, State 3
Attempt to insert duplicate key row in object 'Spot' with unique index 'XPKSpot'
Command has been aborted.

The datatype of this column is int, and number of rows ~17000.
If I execute select @@identity it returns null.

View 4 Replies View Related

WHERE With An Alias Doesn't Work

Aug 2, 2004

I'm combining first name, last name, middle name, and an ID number together into an alias. Then I need to match that alias with a variable passed to the page (its a search results page). The problem is it claims that there is no table with the name of my alias. Anyone know what I'm doing wrong?

A mockup of the SQL looks like this:

SELECT UserID, Last_Name + ', ' + First_Name + ' ' + Middle_Name + '.' AS name
FROM Table
WHERE name LIKE 'variable%'


Everything looks right with the results, if I take out the WHERE clause it has name displayed properly and joined together with the rest of the data in the results properly.

Thanks in advance for any help that can be provided!

View 3 Replies View Related

Linkserver Doesn't Work.

Oct 12, 2007

I have a query that doesn't work when i use 4 name convention instead of a openquery. The msg is below. Anyone know what is going on?
Both queries are the same but one doesn't work.

-- works
SELECT TOP 1 * FROM OPENQUERY(AS400_PROD, 'SELECT * FROM PPTREASUSA.ORDDET')

-- doesnt work
SELECT TOP 1 * FROM AS400_PROD.S1030Y3M.PPTREASUSA.ORDDET



Server: Msg 7399, Level 16, State 1, Line 1
OLE DB provider 'MSDASQL' reported an error.
[OLE/DB provider returned message: Unspecified error]
[OLE/DB provider returned message: [IBM][iSeries Access ODBC Driver][DB2 UDB]CPF5715 - File ORDDET01 in library QTEMP not found.]
OLE DB error trace [OLE/DB Provider 'MSDASQL' IDBSchemaRowset::GetRowset returned 0x80004005: ].





http://www.sqlserverstudy.com

View 2 Replies View Related

Sp_send_dbmail Doesn't Work

Jan 17, 2008

hi all,
i made a stored procedure that uses the sp_send_dbmail to send mails. SQL server dislays the message "mail queued" but nothing is recieved

here is the code of the stored procedure i made
EXEC msdb.dbo.sp_send_dbmail
@profile_name = 'Exams',
@recipients = 'me@domain.com',
@Body_format = 'HTML' ,
@subject = 'Room Preparation' ,
@body='hi there';
so can anyone help with this issue
thanks in advance

View 6 Replies View Related

Drill Through Doesn't Work.

Feb 7, 2007

I have a drill through that passes four parameters. Three are passed from the current selections in that reports parameters and the fourth needs to be the customer name they click on in the body of the report so it's passed as Fields!fieldname.Value. When I click on the customer name, the drillthough fires but the report simply doesn't load. If I remove the parameter from the field clicked on and just pass the three parameters, it goes to the drill through correctly and that fourth parameter just sets to the default for that parameter in that report.

I can then simply check that parameter and select the value from the list that is exactly the same as the value I was attempting to pass it in the drill through and report refreshes correctly.

Whatever it is, is something in the manner that the value is passed in the drill through specifically.

Any ideas?

View 1 Replies View Related

Using SP_ATTACH_SINGLE_FILE_DB Doesn't Work.

Mar 15, 2007

Hello,
I've rescued a MDF and LDF files off a client's old server, and I wanted to attach it to our own, but I can't seem to get the command to work, basically I have these two files, which I've dropped on our server:

C:Program FilesMicrosoft SQL ServerMSSQLDataMYCLIENTNAME_Data.MDF
C:Program FilesMicrosoft SQL ServerMSSQLDataMYCLIENTNAME_Data.LDF

So when I do a
SP_ATTACH_SINGLE_FILE_DB 'somedb','C:Program FilesMicrosoft SQL ServerMSSQLDataMYCLIENTNAME_Data.MDF'

It says the LDF path my be incorrect, and that there's two other files that are missing:
MYCLIENTNAME_LOG (no extension)
extra_log (no extension)

I thought the whole point of the command is that you only need a single file?
Its very hard to go back to the client's old server and try to find these two files, and it doesn't really matter if we loose a bit of data, so long as the bulk of it is available.

Update: I think I've found the answer...its not possible to do this, it really needs all the log files.
Any workarounds?

View 1 Replies View Related

Why Doesn't This DecryptByKeyAutoCert Work?

Jun 25, 2007

This works:



-- authenticator

CREATE FUNCTION [dbo].[cc2_Helper]( @SecretData VARBINARY(256), @cId INT )

RETURNS NVARCHAR(50)

WITH EXECUTE AS 'DBO'

AS

BEGIN

RETURN convert( NVARCHAR(50), decryptbykeyautocert( cert_id( 'cert_SecretTable_SecretData_Key' ), null, @SecretData, 1, convert(varbinary, @cId) ) )

END

go

CREATE VIEW [dbo].[cc2View2]

AS

SELECT CardID as CardID, [dbo].[cc2_Helper](CardNumber, CardID) as CardNumber FROM [dbo].[cc2]

go

GRANT SELECT ON [dbo].[cc2View2] TO [user_low_priv]





This doesn't:



-- auth2/view3

CREATE FUNCTION [dbo].[cc2_Helper2]( @SecretData VARBINARY(256), @vBin VARBINARY )

RETURNS NVARCHAR(50)

WITH EXECUTE AS 'DBO'

AS

BEGIN

RETURN convert( NVARCHAR(50), decryptbykeyautocert( cert_id( 'cert_SecretTable_SecretData_Key' ), null, @SecretData, 1, @vBin ) )

END

go

CREATE VIEW [dbo].[cc2View3]

AS

SELECT CardID as CardID, [dbo].[cc2_Helper2](CardNumber, convert(varbinary, CardID)) as CardNumber FROM [dbo].[cc2]

go

GRANT SELECT ON [dbo].[cc2View3] TO [user_low_priv]



WHY? Note that the conversion to VARBINARY was moved from the call to DecryptByKeyAutoCert to the call to cc2_Helper2. That is the only change...



But if I declare @vBin as VARBINARY(256) then it does work! Guess I'm a little confused on declaring vars...anyone can elucidate? Thanks.

View 1 Replies View Related

SQLDS Doesn't Work Well With Uniqueidentifier ?

Dec 25, 2005

In the Data Source Wizard the "insert,delete,update" advanced options are greyed out.

The table's PK is not an identity, but a uniqueidentifier.

View 2 Replies View Related

STUMPED: Why Doesn't This Procedure Work?

Jan 16, 2006

I have been looking at this for over a day now. I cannot see why this procedure does not work, its so simple.
No matter what happens it always returns 0. If it locates a record, it doesnt update it, yet it still returns 0.
It should not be returning 0 if its not updating so I can't figure out why it does.
Why does this always return 0?
[pre]Create Procedure CreateNewCategory @title nvarchar(100), @description nvarchar(1000), @displayOrder intAS DECLARE @Result as int
IF EXISTS(SELECT categoryTitle FROM categories WHERE categoryTitle = @title) BEGIN  SELECT @Result = 1 ENDELSE BEGIN  INSERT INTO categories(categoryTitle, categoryDescription, displayOrder)  VALUES(@title, @description, @displayOrder)   /* If no error was encountered, 0 will be returned. */  SELECT @Result = @@Error ENDGO[/pre]
Thanks!
 

View 2 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved