Help: How Do I Change Database Within An Opened Cursor Block??
Dec 4, 2007
Hi All:
Can anyone point out what's wrong with the following script? I wanted to print all the LOGFILE names in all databases which are not in SIMPLE recovery model. Thanks in advance.
Jim
USE masterDECLARE @db_name nvarchar(100), @log_name nvarchar(100);DECLARE DB_Cursor CURSOR FORselect name from msdb.sys.databases where recovery_model_desc <> 'SIMPLE';OPEN DB_Cursor FETCH NEXT FROM DB_Cursor INTO @db_name WHILE @@FETCH_STATUS = 0 BEGIN USE @db_name -- Can I do this? GO select @log_name = name from sys.database_files where type_desc ='LOG'; print @log_name; ENDCLOSE DB_CursorDEALLOCATE DB_CursorI got the following error:Msg 102, Level 15, State 1, Line 13Incorrect syntax near '@db_name'.Msg 137, Level 15, State 1, Line 1Must declare the scalar variable "@log_name".Msg 137, Level 15, State 2, Line 2Must declare the scalar variable "@log_name".
Using SQL native client from VFP 9.0 to SQL Server 2005 64 bit SP1 (happened before SP1 too)..
We have a stored procedure that returns 6 result sets. This SP uses 2 cursors. It is rather lengthy - I'll post the code if needed.
This SP works fine when called from VFP 99 percent of the time. Normally takes 2 to 3 secunds to execute.
Once in a while we will get a return from SQL ..
"OLE IDispatch exception code 0 from Microsoft SQL Native Client: A server cursor cannot be opened on the given statement or statements. Use a default result set or client cursor..."
The OLE error code is 1429. An OLE Exception code 3604 is also returned.
When this happens the SP will return the same error when executed for the same parameters over and over when called from VFP. When called directly from SQL management console it will normally work for the same parameters, although once in a while it will just hang (and not timeout apparently). In that case it will also hang from SQLCMD command line utility as well.
Wait a few hours and the SP will run fine for the same parameters in VFP. This happens even in the middle of the night when there is no possibility that data is being changed.
Here's the really fun part...
Open the SP source for modification (ALTER PROCEDURE) in management console and execute it (no changes at all, just let it recompile). Immediately it will work fine when called with the same parameters called from VFP or anywhere else (even if it was one of the rare instances where it hung in management console). This works EVERY TIME.
Sooo... I edited and executed the SP with the WITH RECOMPILE option assuming that that should do the trick (same as alter procedure/executing from management console right?). NOPE. Same problems. In order to work around the problem when the error occurs, I HAVE TO alter procedure and execute the code from management console.
hi there, to retrieve more then one record with a cursor we can use block cursor, so we have to set the cursor attribute SQL_ATTR_ROWSET_SIZE to some number...i am not getting any code example on this. do anyone know this???
I like to backup the stored procedures' code used in my databases. So I created this Script:
/* IF OBJECT_ID('[Monitor].[dbo].[Procedurecode]') IS NOT NULL DROP TABLE [Monitor].[dbo].[Procedurecode]; */ DECLARE @db nvarchar(50), @strSQL nvarchar (100) IF CURSOR_STATUS('global','cur1')>=-1 BEGIN DEALLOCATE cur1 END
[code]....
Problem is (and I seem not to be the only one with tis) described here:
"If the executed string contains a USE statement that changes the database context, the change to the database context only lasts until sp_executesql or the EXECUTE statement has finished running." There is nothing magical in SQL server that knows you intend a series of dynamic sql commands to be part of a single job running in a single context. You have to build the entire string for the job you want to execute."
I'am doing functionality test on DTS packages and saving my DTS packages to meta data services instead of saving them as local packages. We would like to see what information would be provided by saving them this way, but when we try to open the meta data browser (the 3rd icon under DTS) we get the following error:
An error occurred while trying to access the database information. The msdb database could not be opened.
I'm working on a SQL Server 2005 mirroring database test.The idea is to stop main DB server and activate the standby being mirrored (pretendng that principal DB Server is down)
Mirror works fine. But for the test I do the following:
- Stop the principal SQLSERVER - Connect to the standby server and execute the followng:
Hello,Could you explain me please the following error:"Database 'DemoDotNET' cannot be opened due to inaccessible files orinsufficient memory or disk space. (Microsoft SQL Server, Error: 945)"I have checked: free disk space is large enough, I have much enoughmemory, other files in the directory are accessible.Here is tail of ERRORLOG:2006-06-12 21:19:55.68 Logon Error: 18456, Severity: 14, State:16.2006-06-12 21:19:55.68 Logon Login failed for user 'PCRobert'.[CLIENT: <local machine>]2006-06-12 21:20:43.39 Server Server resumed execution afterbeing idle 1 seconds: user activity awakened the server. This is aninformational message only. No user action is required.Please help to solve this.Thank you./RAM/
I opened SQL Server management studio and tried to connect with the local database and received the error message:
Database 'msdb' cannot be opened. It has been marked suspect.....
I have pasted the only error from the event log I could find below, but it doesn't mean much to me.
In the event I can't find what the problem is, and not being a database administrator, can anyone tell me what I can do to get back in working order without messing up all the databases in my SQL Server 2005. I'm afraid I only have a MASTER backup from several months ago, and am afraid if I use this, I will loose the latest data. I'm a novice, and do not understand the relationship of the master/msdb/model databases to my core custom databases. Can I do some sort of master rebuild without affecting the other databases I have?
I have tried sp_resetstatus but this didn't fix the problem, but it did enable me to actually connect to the SQL server instance so I could access all the other databases.
Many thanks Gerard
Event log error detail:
The log scan number (152:284:1) passed to log scan in database 'msdb' is not valid. This error may indicate data corruption or that the log file (.ldf) does not match the data file (.mdf). If this error occurred during replication, re-create the publication. Otherwise, restore from backup if the problem results in a failure during startup.
When I try the open the report file, I got the following error message. Database 'ReportServer$SQLExpressTempDB' cannot be opened due to inaccessible files or insufficient memory or disk space. See the SQL Server errorlog for details. Anyony have ideas to fix this error?
I have the following stored procedure to test scope of variables
alter proc updatePrereq @pcntr int, @pmax int as begin
[Code] ....
In the above script @i is declare in the if block only when the @pcntr value is 1. Assume the above stored procedure is called 5 times from this script
declare @z int set @z = 1 declare @max int set @max = 5 while @z <= @max begin exec dbo.updatePrereq @z, @max set @z = @z + 1 end go
As i said earlier `@i` variable exists only when `@pcntr` is `1`. Therefore when i call the stored procedure for the second time and so forth the control cannot enter the if block therefore @i variable wouldn't even exist. But the script prints the value in `@i` in each iteration, How comes this is possible should it throw an error saying `@i` variable does not exist when `@pcntr` values is greater than `1`?
I have a view saved on server - mhsvi-datawarehousedatawarehouse.This view, in it's TSQL connects to a databasethat is set up as a linked server. That server is mhsvi-sql2008ainstance1.When I try to add the view to Excel in order to automatically refresh for users as a report - I get the following error - (I get it as well)
The query did not run, or the database table could not be opened.Check the database server or contact your database administrator. Make sure the external database is available and hasn't been moved or reorganized, then try the operation again.I have access to the database where the view is saved and the database that the TSQL calls.
Greetings, I have just arrived back into the country (NZ) and back into ASP.NET. I am having trouble with the following:An attempt to attach an auto-named database for file (file location).../Database.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share. It has only begun since i decided i wanted to use IIS, I realise VWD comes with its own localhost, but since it is only temporary, i wanted a permanent shortcut on my desktop to link to my intranet page. Anyone have any ideas why i am getting the above error? have searched many places on the internet and not getting any closer. Cheers ~ J
I have been playing with a Standard Version of VS 2005 and SSE 2005 and I just cannot get these two to interact together well. I am sure it is a noob problem but I have seen this error addressed on this forum and I am just not getting it. Here is exactly what I am doing.
I want to create a database within SSE using the Management Studio. Then, I want to connect to it with VS2005. Both SSE and VS2005 are local. I just cant seem to get this to work.
I always seem to get this error "An attempt to attach an auto-named database for file C:Program FilesMicrosoft SQL ServerMSSQL.1MSSQLDataSecond.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share."
One thing... I create the website with Location: HTTP. I don't even know anymore why I do this.. I think because I like to be able to pull up a browser and get to my app. Other than that I am doing nothing special. However, I get the above error when I hit F5 to run the app inside VS2005.
Is there someplace where a complete noob can find a thorough and simple covering of this? Again, I have read through some of the previous posts on this and I don't understand too many of them and it seems as if there are at least 13 causes of which I don't know which one I have. Help!
If you are having trouble accessing Meta Data Services on W2k3 and SQL 2000 and get the error that the "msdb database could not be opened" I found that hot fix 912812 on the operating system is the culprit. Remove it and Meta Data goes back to working, although I am being asked to approve the ActiveX control every time the page refreshes.
Hope this helps somebody, to took me long enough to track it down.
If anyone has a resolution to the ActiveX question I'd love to know the answer.
The db that I took over is full of !@##$@, unnormalized tables, cursors, you name it and it has it :(.
There is this cursor that opens a temp table, fetches the key and then deletes from the production table using that key for every row in the temp table.
I want to change it to something like
delete from A where exists (select 1 from B where B.ID1 = A.ID1 and B.ID2 = A.ID2)
Now, I'm thinking that this query would secuentially scan A and compare the key to what B has and that is a waste of time. Is there a way to do it the other way around ? Scan the rows on table B and then delete them from table A ?
I haven't really played with sql in some time, maybe the answer is trivial but I can't see it right now.
I am trying to loop through databases to gather information.
However if i loop though datbases in a cursor, by using a select from sysdatabases, once i am in the cursor and SET @Sql = 'use ' + DBName and EXEC(SQL), the database context never changes from the one the cursor is executing in.
Is there a way to loop through database contexts and execute sql ?
but after the assignment the LocalConnectionString is different from ConnectionStringWithoutCredentials, there are much more ssce parameters.
What I don't understand is:
why I'm getting this error even after closing the connection ?
Since the error report [32] the ssce conflicting parameters shoud be AUTO_SHRINK_THRESHOLD, FLUSH_INTERVAL and MAX_DATABASE_SIZE
I tried to cut & paste the same values from LocalConnectionString into app.config connection string, at first It seemed to work, but now I got the same error.
I have been experiencing a lot of blocking activity in my database. My trace results show that the following extended stored procedures sp_prepexec and sp_cursorfetch are executed by both the user causing the block and the user tha is blocked. Any ideas as to how to rectify this situation will be appreciated.
have created a Database Application in Java and display all the records in tabular format of one Table. This table have Millions of Rows, If I run Select * from Table, then my Machine not responding, so Now I wants to add paging of 1000 rows at one time.
Is there are any option/query to read block of rows at one time and then query again for next page ?
i.e In MYSQL have LIMIT clause with Select Statement
I am trying to add the hours between each time block stored in a database.
In this database a user enters the begin time and the end time. For example the course MATH0001 would start at 8am and end at 10am. Therefore the user would enter 0810 in the start field and 1000 in the end field. The course MATH0001 doesn't run the entire semester it may only run from 8th Jan - 15th March and the course is scheduled in a room called GR4. Now because a course can be scheduled modularly, one room could have several courses scheduled in this manner.
The problem: I need to find out how many hours GR4 is used but it contains the following courses
A day only has 13 hours. Therefore the total hours spent in GR4 should be 12 hours. This is calculated by adding the hours between 8am and 5pm = 9 hours and 5pm an 8pm = 3 hours. I would not include 9am to 1pm because it is a subset of the 8am to 5pm slot.
Now, how to accomplish this but below is the code that i have thus far:
I forgot to mention that this code was to just test my 'final code' results and it outputs the table shown above. Anyway for testing purposes I have limited the search to the room GR4 and the day Tuesdays.
Code: select DISTINCT ssrmeet_room_code, ssrmeet_start_date, ssrmeet_end_date, ssrmeet_crn, ssrmeet_begin_time, ssrmeet_end_time, (((CAST(M.SSRMEET_END_TIME AS INT))-(CAST(M.SSRMEET_BEGIN_TIME AS INT)))+10)/100 As HoursPerClass,
I have tried to attatch a database ,created by SQL server Express within a C# application , in SQL server 2005 Enterprise edition, but the following error message appears:
-----------------------------
TITLE: Microsoft SQL Server Management Studio ------------------------------
Attach database failed for Server 'MEDO'. (Microsoft.SqlServer.Smo)
For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft SQL Server&ProdVer=9.00.1187.00&EvtSrc=Microsoft.SqlServer.Management.Smo.ExceptionTemplates.FailedOperationExceptionText&EvtID=Attach database+Server&LinkId=20476
An exception occurred while executing a Transact-SQL statement or batch. (Microsoft.SqlServer.ConnectionInfo)
------------------------------
The database 'E:X.MDF' cannot be opened because it is version 611. This server supports version 607 and earlier. A downgrade path is not supported. Could not open new database 'E:X.MDF'. CREATE DATABASE is aborted. (Microsoft SQL Server, Error: 948)
------------------------------
so , how can I solve this problem , I need to reed the data resides in the tables of 'X' database , how can I do it?? please help me.
Now, I checked and verified that my backup version of SQL Server is the same as the version installed on the computer I'm restoring too.
I have SQL Server on a production machine that I backed up and want to test a full restore on a dev machine to make sure it will work when I need it to.
Now that I've run the restore command on my tape backup and go to restart the SQL server service I receive:
Configuration block version 0 is not a valid version number. SQL Server is exiting. Restore the master database or reinstall.
I'm afraid I don't understand why this is happening. If the builds are the same, then shouldn't restoring the MASTER database have worked normally and I'd be able to restart the service now?
The default web diretory works on my locathost,but when I upload to the free website, http://dehim.aspx.sk/ I'm getting the following error. The database 'D:LOCALUSERDEHIMAPP_DATAWAPDATABASE.MDF' cannot be opened because it is version 611. This server supports version 603 and earlier. A downgrade path is not supported.Could not open new database 'D:LOCALUSERDEHIMAPP_DATAWAPDATABASE.MDF'. CREATE DATABASE is aborted.An attempt to attach an auto-named database for file D:LocalUserdehimApp_DataWapDatabase.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share. How do I downgrade the database to match server?
I was trying to update a named instance of SQL Express SP1. I double clicked it and during extraction I get this error message:
The file C:Document and SettingsByersNLocal SettingsTempBSISQLEXP05TRACTsetupsqlcli.msi could not be opened.
SQL Express came bundled with another porgram so I'm thining it could be a bad cd. I also thought about reinstalling Windows Installer 3.1. Anybody experience this error?
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.
Hello,I have a test database with table A containing 10,000 rows and a tableB containing 100,000 rows. Rows in B are "children" of rows in A -each row in A has 10 related rows in B (ie. B has a foreign key to A).Using ODBC I am executing the following loop 10,000 times, expressedbelow in pseudo-code:"select * from A order by a_pk option (fast 1)""fetch from A result set""select * from B where where fk_to_a = 'xxx' order by b_pk option(fast 1)""fetch from B result set" repeated 10 timesIn the above psueod-code 'xxx' is the primary key of the current Arow. NOTE: it is not a mistake that we are repeatedly doing the Aquery and retrieving only the first row.When the queries use fast-forward-only cursors this takes about 2.5minutes. When the queries use dynamic cursors this takes about 1 hour.Does anyone know why the dynamic cursor is killing performance?Because of the SQL Server ODBC driver it is not possible to havenested/multiple fast-forward-only cursors, hence I need to exploreother alternatives.I can only assume that a different query plan is getting constructedfor the dynamic cursor case versus the fast forward only cursor, but Ihave no way of finding out what that query plan is.All help appreciated.Kevin
I'm trying to implement a sp_MSforeachsp howvever when I call sp_MSforeach_worker I get the following error can you please explain this problem to me so I can over come the issue.
Msg 16958, Level 16, State 3, Procedure sp_MSforeach_worker, Line 31
Could not complete cursor operation because the set options have changed since the cursor was declared.
Msg 16958, Level 16, State 3, Procedure sp_MSforeach_worker, Line 32
Could not complete cursor operation because the set options have changed since the cursor was declared.
Msg 16917, Level 16, State 1, Procedure sp_MSforeach_worker, Line 153
Cursor is not open.
here is the stored procedure:
Alter PROCEDURE [dbo].[sp_MSforeachsp]
@command1 nvarchar(2000)
, @replacechar nchar(1) = N'?'
, @command2 nvarchar(2000) = null
, @command3 nvarchar(2000) = null
, @whereand nvarchar(2000) = null
, @precommand nvarchar(2000) = null
, @postcommand nvarchar(2000) = null
AS
/* This procedure belongs in the "master" database so it is acessible to all databases */
/* This proc returns one or more rows for each stored procedure */
/* @precommand and @postcommand may be used to force a single result set via a temp table. */
declare @retval int
if (@precommand is not null) EXECUTE(@precommand)
/* Create the select */
EXECUTE(N'declare hCForEachTable cursor global for
Using the sys.databases & sys.sysindexes views to display all the columns with a clustered index for all tables and all databases in a given server. So the end result will have 3 columns:
Database name Table name Column name from that table with a clustered index
I have already created the following script which displays all the databases for a given server:
declare @DBname nvarchar(128) declare testCursorForDB cursor for select name from sys.databases with (nolock) where name not in ('master','tempdb','model','msdb') order by name
open testCursorForDB fetch next from testCursorForDB into @DBname
while @@fetch_status = 0 begin print @DBname fetch next from testCursorForDB into @DBname end
close testCursorForDB deallocate testCursorForDB
I also have created the following query which will display all the table and column names which have a clustered index for a given database:
select object_name(i.id) as TableName,
i.name as IndexName from sys.sysindexes as i with (nolock) where i.indid = '1'
However, what I need help/advice on is how do I combine these two together into one working script (either using nested cursors or a better way). In other words, how can I specify which database to use (ie. using the "use database_name") so that my query above will be applied to each database found within the cursor.