Showing posts with label stored. Show all posts
Showing posts with label stored. Show all posts

Wednesday, March 21, 2012

Recover System Stored Procedure

I mistakenly deleted the system stored procedure 'sp_columns' from my MSDE. Any idea about how to recover/reinstall it back without reinstalling the entire MSDE? Please help. Thanks.

you could restore your master database if you've a recent copy. Alternatively, the following script will recreate it. You'll need to either run it via a GUI tool, or else use osql from Dos.

use master
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO


/* Procedure for 8.0 server */
CREATE PROCEDURE sp_columns (
@.table_name nvarchar(384),
@.table_owner nvarchar(384) = null,
@.table_qualifier sysname = null,
@.column_name nvarchar(384) = null,
@.ODBCVer int = 2)
AS
DECLARE @.full_table_name nvarchar(769)
DECLARE @.table_id int

if @.ODBCVer <> 3
select @.ODBCVer = 2
if @.column_name is null /* If column name not supplied, match all */
select @.column_name = '%'
if @.table_qualifier is not null
begin
if db_name() <> @.table_qualifier
begin /* If qualifier doesn't match current database */
raiserror (15250, -1,-1)
return
end
end
if @.table_name is null
begin /* If table name not supplied, match all */
select @.table_name = '%'
end
if @.table_owner is null
begin /* If unqualified table name */
SELECT @.full_table_name = quotename(@.table_name)
end
else
begin /* Qualified table name */
if @.table_owner = ''
begin /* If empty owner name */
SELECT @.full_table_name = quotename(@.table_owner)
end
else
begin
SELECT @.full_table_name = quotename(@.table_owner) +
'.' + quotename(@.table_name)
end
end

/* Get Object ID */
SELECT @.table_id = object_id(@.full_table_name)
if ((isnull(charindex('%', @.full_table_name),0) = 0) and
(isnull(charindex('[', @.table_name),0) = 0) and
(isnull(charindex('[', @.table_owner),0) = 0) and
(isnull(charindex('_', @.full_table_name),0) = 0) and
@.table_id <> 0)
begin
/* this block is for the case where there is no pattern
matching required for the table name */

SELECT
TABLE_QUALIFIER = convert(sysname,DB_NAME()),
TABLE_OWNER = convert(sysname,USER_NAME(o.uid)),
TABLE_NAME = convert(sysname,o.name),
COLUMN_NAME = convert(sysname,c.name),
d.DATA_TYPE,
convert (sysname,case
when t.xusertype > 255 then t.name
else d.TYPE_NAME collate database_default
end) TYPE_NAME,
convert(int,case
when d.DATA_TYPE in (6,7) then d.data_precision /* FLOAT/REAL */
else OdbcPrec(c.xtype,c.length,c.xprec)
end) "PRECISION",
convert(int,case
when type_name(d.ss_dtype) IN ('numeric','decimal') then /* decimal/numeric types */
OdbcPrec(c.xtype,c.length,c.xprec)+2
else
isnull(d.length, c.length)
end) LENGTH,
SCALE = convert(smallint, OdbcScale(c.xtype,c.xscale)),
d.RADIX,
NULLABLE = convert(smallint, ColumnProperty (c.id, c.name, 'AllowsNull')),
REMARKS = convert(varchar(254),null), /* Remarks are NULL */
COLUMN_DEF = text,
d.SQL_DATA_TYPE,
d.SQL_DATETIME_SUB,
CHAR_OCTET_LENGTH = isnull(d.length, c.length)+d.charbin,
ORDINAL_POSITION = convert(int,
(
select count(*)
from syscolumns sc
where sc.id = c.id
AND sc.number = c.number
AND sc.colid <= c.colid
)),
IS_NULLABLE = convert(varchar(254),
substring('NO YES',(ColumnProperty (c.id, c.name, 'AllowsNull')*3)+1,3)),
SS_DATA_TYPE = c.type
FROM
sysobjects o,
master.dbo.spt_datatype_info d,
systypes t,
syscolumns c
LEFT OUTER JOIN syscomments m on c.cdefault = m.id
AND m.colid = 1
WHERE
o.id = @.table_id
AND c.id = o.id
AND t.xtype = d.ss_dtype
AND c.length = isnull(d.fixlen, c.length)
AND (d.ODBCVer is null or d.ODBCVer = @.ODBCVer)
AND (o.type not in ('P', 'FN', 'TF', 'IF') OR (o.type in ('TF', 'IF') and c.number = 0))
AND isnull(d.AUTO_INCREMENT,0) = isnull(ColumnProperty (c.id, c.name, 'IsIdentity'),0)
AND c.xusertype = t.xusertype
AND c.name like @.column_name
ORDER BY 17
end
else
begin
/* this block is for the case where there IS pattern
matching done on the table name */

if @.table_owner is null /* If owner not supplied, match all */
select @.table_owner = '%'

SELECT
TABLE_QUALIFIER = convert(sysname,DB_NAME()),
TABLE_OWNER = convert(sysname,USER_NAME(o.uid)),
TABLE_NAME = convert(sysname,o.name),
COLUMN_NAME = convert(sysname,c.name),
d.DATA_TYPE,
convert (sysname,case
when t.xusertype > 255 then t.name
else d.TYPE_NAME collate database_default
end) TYPE_NAME,
convert(int,case
when d.DATA_TYPE in (6,7) then d.data_precision /* FLOAT/REAL */
else OdbcPrec(c.xtype,c.length,c.xprec)
end) "PRECISION",
convert(int,case
when type_name(d.ss_dtype) IN ('numeric','decimal') then /* decimal/numeric types */
OdbcPrec(c.xtype,c.length,c.xprec)+2
else
isnull(d.length, c.length)
end) LENGTH,
SCALE = convert(smallint, OdbcScale(c.xtype,c.xscale)),
d.RADIX,
NULLABLE = convert(smallint, ColumnProperty (c.id, c.name, 'AllowsNull')),
REMARKS = convert(varchar(254),null), /* Remarks are NULL */
COLUMN_DEF = text,
d.SQL_DATA_TYPE,
d.SQL_DATETIME_SUB,
CHAR_OCTET_LENGTH = isnull(d.length, c.length)+d.charbin,
ORDINAL_POSITION = convert(int,
(
select count(*)
from syscolumns sc
where sc.id = c.id
AND sc.number = c.number
AND sc.colid <= c.colid
)),
IS_NULLABLE = convert(varchar(254),
rtrim(substring('NO YES',(ColumnProperty (c.id, c.name, 'AllowsNull')*3)+1,3))),
SS_DATA_TYPE = c.type
FROM
sysobjects o,
master.dbo.spt_datatype_info d,
systypes t,
syscolumns c
LEFT OUTER JOIN syscomments m on c.cdefault = m.id
AND m.colid = 1
WHERE
o.name like @.table_name
AND user_name(o.uid) like @.table_owner
AND o.id = c.id
AND t.xtype = d.ss_dtype
AND c.length = isnull(d.fixlen, c.length)
AND (d.ODBCVer is null or d.ODBCVer = @.ODBCVer)
AND (o.type not in ('P', 'FN', 'TF', 'IF') OR (o.type in ('TF', 'IF') and c.number = 0))
AND isnull(d.AUTO_INCREMENT,0) = isnull(ColumnProperty (c.id, c.name, 'IsIdentity'),0)
AND c.xusertype = t.xusertype
AND c.name like @.column_name
ORDER BY 2, 3, 17
end

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO

|||Cathal, thanks a lot!

Recover structure from corrupt .MDF?

Hi,
I have a corrupt .mdf file and all I want to do is get the stored procedures
& table structure out of the file. Is this possible? (I do not have a
backup ).
cheers
James"James" <jamese@.dontspam.com> wrote in message
news:ONeoYLzeGHA.4976@.TK2MSFTNGP02.phx.gbl...
> Hi,
> I have a corrupt .mdf file and all I want to do is get the stored
> procedures & table structure out of the file. Is this possible? (I do not
> have a backup ).
That depends on the level of corruption. As long as the procedures weren't
encrypted, they are stored in the MDF file as text and may be fished out.
The tables are another story.|||You are a bl**dy star....I'm so stupid, I should have thought to open the
file as a text file. Thank you so much!!!
James
"BDB" <bdb@.reply.to.group.com> wrote in message
news:OnmhcV1eGHA.3900@.TK2MSFTNGP05.phx.gbl...
> "James" <jamese@.dontspam.com> wrote in message
> news:ONeoYLzeGHA.4976@.TK2MSFTNGP02.phx.gbl...
>> Hi,
>> I have a corrupt .mdf file and all I want to do is get the stored
>> procedures & table structure out of the file. Is this possible? (I do not
>> have a backup ).
> That depends on the level of corruption. As long as the procedures
> weren't encrypted, they are stored in the MDF file as text and may be
> fished out. The tables are another story.
>

Recover structure from corrupt .MDF?

Hi,
I have a corrupt .mdf file and all I want to do is get the stored procedures
& table structure out of the file. Is this possible? (I do not have a
backup ).
cheers
James"James" <jamese@.dontspam.com> wrote in message
news:ONeoYLzeGHA.4976@.TK2MSFTNGP02.phx.gbl...
> Hi,
> I have a corrupt .mdf file and all I want to do is get the stored
> procedures & table structure out of the file. Is this possible? (I do not
> have a backup ).
That depends on the level of corruption. As long as the procedures weren't
encrypted, they are stored in the MDF file as text and may be fished out.
The tables are another story.|||You are a bl**dy star....I'm so stupid, I should have thought to open the
file as a text file. Thank you so much!!!
James
"BDB" <bdb@.reply.to.group.com> wrote in message
news:OnmhcV1eGHA.3900@.TK2MSFTNGP05.phx.gbl...
> "James" <jamese@.dontspam.com> wrote in message
> news:ONeoYLzeGHA.4976@.TK2MSFTNGP02.phx.gbl...
> That depends on the level of corruption. As long as the procedures
> weren't encrypted, they are stored in the MDF file as text and may be
> fished out. The tables are another story.
>

Recover stored procedures

Before my hard disk failed , I had backup MSSQL7 folder.After I re format it and attached the database [MDF ,LDF ] I lost my stored procedures.Can someone help me or show me how to recover my stored procedures.
Thanks.The SPs are part of the database and should be there if the database is not corrupt.
Maybe they are owned by a different user or mapped to a different login.
Try select * from sysobjects where type = 'P'
and look in syscomments

select text from syscomments where text like '%myspname%'|||Thanks for your fast response , I am so lucky that get back my 150 stored procedures back from my old 500 MB hard disk !!!

Thanks.sql

Friday, March 9, 2012

recover a stored procedure

If I can't connect to my database and my test server requires a reinstall of SQL Server 2005, how can I get my one stored proc out of there and back it up if I can't even connect to my database? Is there a file that is created that may have this? I know it's probably stored in master or something but not sure if it can be recovered.Before reinstalling the SQL Server, make a copy of the database files (.MDF and .LDF) in which you created your stored proc. When the new instance is installed, attach the DB and retrieve your stored proc from there.

Wednesday, March 7, 2012

RecordSet into a DataFlow Task

In the control flow I have an "Execute SQL Task" that executes a stored procedure. The stored procedure returns a result set of about 2000 rows of data into a package variable that has been typed as Object to contain the data.

What I have not been able to figure out is how to access the rows of data (in the package variable) from within a data flow task. There does not seem to be a data flow source task to perform that operation.

What am I missing that would make this easy?

...cordell...

if you need to have control on every row of the result set you may be on the need of using a data flow task(source, transforms and destination components). Would you give an example of what you are trying to accomplish after getting the 2000 rows?

|||

In the data flow task...I need to parse through the data to generate 3 unique result sets of data. One of the result sets will go to a text file, the 2nd result set go back into a staging table, and the 3rd result set goes to a excel spreadsheet.

|||

Cordell Swannack wrote:

In the control flow I have an "Execute SQL Task" that executes a stored procedure. The stored procedure returns a result set of about 2000 rows of data into a package variable that has been typed as Object to contain the data.

What I have not been able to figure out is how to access the rows of data (in the package variable) from within a data flow task. There does not seem to be a data flow source task to perform that operation.

What am I missing that would make this easy?

...cordell...

This shows you how to do it:

Recordsets instead of raw files
(http://blogs.conchango.com/jamiethomson/archive/2006/01/04/2540.aspx)

I'm not sure if this is relevant though. If you are using a SQL statement to get the data why not just put the SQL statement into an OLE DB Source adapter? Why bother with the rigmarole of a variable and then having to write code?

-Jamie

|||

Cordell Swannack wrote:

In the data flow task...I need to parse through the data to generate 3 unique result sets of data. One of the result sets will go to a text file, the 2nd result set go back into a staging table, and the 3rd result set goes to a excel spreadsheet.

I would wager you can accomplish all of this with a combination of the conditional split, multicast and/or derived column components.

Even if you can't, you would be better off employing a script component to parse through the data - there is still no need to put it into a variable first.

-Jamie

|||

Jamie Thomson wrote:

Cordell Swannack wrote:

In the control flow I have an "Execute SQL Task" that executes a stored procedure. The stored procedure returns a result set of about 2000 rows of data into a package variable that has been typed as Object to contain the data.

What I have not been able to figure out is how to access the rows of data (in the package variable) from within a data flow task. There does not seem to be a data flow source task to perform that operation.

What am I missing that would make this easy?

...cordell...

This shows you how to do it:

Recordsets instead of raw files
(http://blogs.conchango.com/jamiethomson/archive/2006/01/04/2540.aspx)

I'm not sure if this is relevant though. If you are using a SQL statement to get the data why not just put the SQL statement into an OLE DB Source adapter? Why bother with the rigmarole of a variable and then having to write code?

-Jamie

I was going to suggest something similar. In general you would use data flows to perform row by row operations; like transformations, splits, sorts, etc. However the control flow may be better place to row set based operations; like an update, select into, etc.

In you particular case, use a dataflow task and then drop a OLE DB source component, any required transform and the detination component.

|||

Helpful suggestions....

While you can use the OLE DB Source adapater inside of the Data Flow task...I am executing a stored procedure that returns back a large result set. When you click on the 'Preview' button...the data and all of the column names are returned. (Just proving that everything works.)

However I haven't figure out how to set the column names typically set by OLE DB Source component. Right now they are blank. Usually at design time when you reference a table or use simple select statement the OLE DB Source task can map the columns specified by the table name or select statement to create a list of columns that are used for the output and thus by other components in the data flow task.

But when executing a stored procedure...the column names are not returned until completion (i.e. runtime) of the stored procedure. This is the problem.

...cordell...

|||

Cordell Swannack wrote:

Helpful suggestions....

While you can use the OLE DB Source adapater inside of the Data Flow task...I am executing a stored procedure that returns back a large result set. When you click on the 'Preview' button...the data and all of the column names are returned. (Just proving that everything works.)

However I haven't figure out how to set the column names typically set by OLE DB Source component. Right now they are blank. Usually at design time when you reference a table or use simple select statement the OLE DB Source task can map the columns specified by the table name or select statement to create a list of columns that are used for the output and thus by other components in the data flow task.

But when executing a stored procedure...the column names are not returned until completion (i.e. runtime) of the stored procedure. This is the problem.

...cordell...

You're absolutely right. This IS a problem with sprocs. And I agree that this sounds like a good justification for using the Execute SQL Task route. However, I suggest another workaround here:

Using stored procedures inside an OLE DB Source component
(http://blogs.conchango.com/jamiethomson/archive/2006/12/20/SSIS_3A00_-Using-stored-procedures-inside-an-OLE-DB-Source-component.aspx)

that you may wish to employ that will enable you to use the OLE DB Source component.

-Jamie

|||

I found your blog entry on the subject just as I was receiving your email.

The reason why a UDF doesn't work for my solution is the amount of transformation processing that must be performed upon the data. Basically I have 10,000's of data records that are processed and then randomized into a laboratory trial groups which are then distributed out to various computer systems for analysis.

I ended up changing around the stored procedure to create a table in the database...and then once the SSIS work has completed...I drop the table. A less than perfect solution...but it gets the job done and it is time to move on.

Thank you Jamie for your time to answer my questions and your patience.

...cordell...

Recordset insert into a table in a SP

Hi,
I need to insert a recordset into a single columns in a table in a Stored procedure.
I have dine the following:
Insert into Staging_Table Values(Recordset)
I get an error that only constants are allowed.
How can I insert the recordset values into that table?RE:
Hi,
I need to insert a recordset into a single columns in a table in a Stored procedure. I have dine the following:
Insert into Staging_Table Values(Recordset)
I get an error that only constants are allowed.
Q1 How can I insert the recordset values into that table?

A1 Insert values inserts (explicit) values. (Try posting the applicable ddl and some sample statements if this is what you are doing.)

For Example:

Use TempDB
Go

CREATE TABLE TestTable ( column_1 varchar(32))
Go

INSERT TestTable VALUES ('Row #1 Value')
INSERT TestTable VALUES ('Row #2 Value')

SELECT * From TestTable|||How do you want to store the recordset in the column and how would you extract information from it once is has been stored in the column ? Please post your existing code.|||Originally posted by rnealejr
How do you want to store the recordset in the column and how would you extract information from it once is has been stored in the column ? Please post your existing code.

Hi,
My existing code is:

if @.col2 is null
Begin
set @.SQL = 'create table LanTable ( ' + @.col1 + ' nvarchar(60))'
exec (@.SQL)
Insert into LanTable SELECT Data1= substring ( Record_Line , @.Pos1,@.Len1) FROM Staging_Table
End
else if @.col3 is null
Begin
set @.SQL = 'create table LanTable ( ' + @.col1 + ' nvarchar(60),' + @.col2 + ' nvarchar(60))'
exec (@.SQL)
Insert into LanTable SELECT Data1= substring ( Record_Line , @.Pos1,@.Len1), Data2= substring ( Record_Line , @.Pos2,@.Len2) FROM Staging_Table
End

@.Pos1,@.Len1,@.col2... all are input parameters of the SP.
Staging_Table consists of one column (Record_Line) that contains the data (ex. 03 Bank 2222 -etc)
Data1 and Data2 are recordsets that each contain their values from the Staging_Table and i want it to be inserted into LanTable.
Can it be done?
Thanks|||Originally posted by garfild
Hi,
My existing code is:

if @.col2 is null
Begin
set @.SQL = 'create table LanTable ( ' + @.col1 + ' nvarchar(60))'
exec (@.SQL)
Insert into LanTable SELECT Data1= substring ( Record_Line , @.Pos1,@.Len1) FROM Staging_Table
End
else if @.col3 is null
Begin
set @.SQL = 'create table LanTable ( ' + @.col1 + ' nvarchar(60),' + @.col2 + ' nvarchar(60))'
exec (@.SQL)
Insert into LanTable SELECT Data1= substring ( Record_Line , @.Pos1,@.Len1), Data2= substring ( Record_Line , @.Pos2,@.Len2) FROM Staging_Table
End

@.Pos1,@.Len1,@.col2... all are input parameters of the SP.
Staging_Table consists of one column (Record_Line) that contains the data (ex. 03 Bank 2222 -etc)
Data1 and Data2 are recordsets that each contain their values from the Staging_Table and i want it to be inserted into LanTable.
Can it be done?
Thanks

Hi again,
Try to use this SP and tell me what i did wrong:

CREATE PROCEDURE Lan_BuildTable
@.col1 nvarchar(60), @.Pos1 int=null, @.Len1 int=null,@.col2 nvarchar(60) = null,@.Pos2 int = null, @.Len2 int=null
AS
declare @.SQL as varchar(3000)

if @.col2 is null
Begin
set @.SQL = 'create table LanTable ( ' + @.col1 + ' nvarchar(60))'
exec (@.SQL)
Insert into LanTable SELECT Data1= substring ( Record_Line , @.Pos1,@.Len1) FROM Staging_Table
End
else if @.col3 is null
Begin
set @.SQL = 'create table LanTable ( ' + @.col1 + ' nvarchar(60),' + @.col2 + ' nvarchar(60))'
exec (@.SQL)
Insert into LanTable SELECT Data1= substring ( Record_Line , @.Pos1,@.Len1), Data2= substring ( Record_Line , @.Pos2,@.Len2) FROM Staging_Table
End

In the VB code I used:
exec Lan_BuildTable OpCode,1,2,Product,4,5

Thanks
Yossi

Recordset does not open with Table Variables

Hello!

I have made an stored procedure that receives 2 parameters and returns a resultset. The resultset is populated from a select made from a table variable declared on that procedure:

select * from @.MyTable

Now, the stored procedure works as expected when invoked on the Query Analizer; but when using a Visual Basic application that uses ADO 2.7, the Recordset object does not open.

What is wrong?

Thanks a lot in advance.Any error?|||Any error?|||Thanks for your reply.

The recordset object does not open; however, a runtime error does not occur.

The visual basic code is very straightforward and has been used with other kind of stored procedures:

Public Sub LoadData()
on error goto E:
Dim objConnection As ADODB.Connection
Dim objCommand As ADODB.Command
Dim objRecordset As ADODB.Recordset
Set objConnection = New ADODB.Connection
objConnection.CursorLocation = adUseClient
objConnection.ConnectionString = m_strConnectionString
objConnection.Open
Set objCommand = New ADODB.Command
Set objCommand.ActiveConnection = objConnection
objCommand.CommandType = adCmdStoredProc
objCommand.CommandText = "myStoredProcedure"
objCommand.Parameters("@.myParameter1").Value = m_varValue1
objCommand.Parameters("@.myParameter2").Value = m_varValue2

Set objRecordset = objCommand.Execute
If objCommand.Parameters(0).Value = 0 Then
do while not objRecordset.EOF
debug.print objRecordset!myField1
objRecordset.MoveNext
loop
End If
Exit sub
E:
MsgBox Err.Description

End Sub

I do not understand why the recordset is not opened. The only difference with other kind of stored procedures that I have used is that the SELECT statement is made from a Table variable:

select * from @.MyTable

The Query Analyzer returns values.

What could be wrong?|||When using Table variable or Temp tables, it is necesary to write "SET NOCOUNT ON" on the top of the stored procedure.

I read that in "PRB: Error Messaging Referencing #Temp Table with ADO-SQLOLEDB", a Microsoft Knowledge Base Article (235340).

http://support.microsoft.com/support/kb/articles/Q235/3/40.ASP

:-D

Recordset destination used in a FOREACH?

Hi all,

Can a Recordset destination be used as source for a ForEach loop.

Correct me if i'm wrong but the Recordset is stored in a variable of type Object? So what stops my ForEach loop from itterating?

Regards,

Pieter

Well, there are about 70-80 examples of using a recordset as a foreach enumerator (source) between BOL, google groups, and this MSDN forum. Shorter answer, yes.

Here's a good example from Jamie Thompson, http://blogs.conchango.com/jamiethomson/archive/2005/07/04/1748.aspx, which not only has verbiage, but a .dtsx file as well.

|||Thanks for the reply. After my post i tried a test project and it worked 100%. I then tried again in my actual project and no luck. Since then I rebuilt my entire work project around the test project and it is still working....go figure

Recordset destination used in a FOREACH?

Hi all,

Can a Recordset destination be used as source for a ForEach loop.

Correct me if i'm wrong but the Recordset is stored in a variable of type Object? So what stops my ForEach loop from itterating?

Regards,

Pieter

Well, there are about 70-80 examples of using a recordset as a foreach enumerator (source) between BOL, google groups, and this MSDN forum. Shorter answer, yes.

Here's a good example from Jamie Thompson, http://blogs.conchango.com/jamiethomson/archive/2005/07/04/1748.aspx, which not only has verbiage, but a .dtsx file as well.

|||Thanks for the reply. After my post i tried a test project and it worked 100%. I then tried again in my actual project and no luck. Since then I rebuilt my entire work project around the test project and it is still working....go figure

Recordset + StoredProcedure ?

I use a recordset for a report

Is a difference between?

1) To use a stored procedure => return a record set

cmd.CommandText = "StoredProcedureName"
cmd.CommandType = adCmdStoredProc
cmd.Execute

Or

2) rs.Open SELECT * FROM , cn, adOpenStatic, adLockReadOnly

__________________________
cn is ADO connection string
cmd is ADO command
rs is ADO RecordsetThe Strore procedure was compiled so is fastest. If the execution plan is still in memory they have not waiting time.

and for the support of your Application if you use at different place your query... with sprocs you need to make de change at only one place... ;)|||Originally posted by Franky
The Strore procedure was compiled so is fastest. If the execution plan is still in memory they have not waiting time.



As regarding the execution plan being stored in Memory .. SQL 2000 also stores the exec plans of all the queries and ages them according to a certain algorithm. So there is really not much difference in that regard.|||and for the support of your Application if you use at different place your query... with sprocs you need to make de change at only one place...

Additionally it is a lot easier to change the stored procedure later on then to change the sql inside your app which would have to be re-compiled and redistributed...|||Originally posted by Ovidiu
I use a recordset for a report

Is a difference between?

1) To use a stored procedure => return a record set

cmd.CommandText = "StoredProcedureName"
cmd.CommandType = adCmdStoredProc
cmd.Execute

Or

2) rs.Open SELECT * FROM ?? cn, adOpenStatic, adLockReadOnly

__________________________
cn is ADO connection string
cmd is ADO command
rs is ADO Recordset

Hi,
I got the experience of this kind of executing a stored procedure and returning a recordset in ASP and VB.
Maybe you can try add this before your last line.
set rs1 = cmd.execute
Then the rs1 is what you want to process next step.
Good lucks

Mosu

Monday, February 20, 2012

Record set to text with separator

Hi all!
I have a bunch of stored procedures that all return record sets. Now I want
the results of these record sets to a file, with a special character to
separate the columns. How can I accomplish that?
Example:
Col1 Col2
-- --
Hi all
Be nice
...should become...
1#Hi#all
2#Be#nice
- Kristoffer -
The easiest way is to run them in Query Analyzer. Go to
Tools/Options/Results and pick Results to File and Custom Delimiter. Then
execute your proc.
Jeff Duncan
MCDBA, MCSE+I
"Kristoffer Persson" <hidden> wrote in message
news:OefzTQqMEHA.2532@.TK2MSFTNGP10.phx.gbl...
> Hi all!
> I have a bunch of stored procedures that all return record sets. Now I
want
> the results of these record sets to a file, with a special character to
> separate the columns. How can I accomplish that?
> Example:
> Col1 Col2
> -- --
> Hi all
> Be nice
> ...should become...
> 1#Hi#all
> 2#Be#nice
> - Kristoffer -
>
>
|||"Jeff Duncan" <jduncan@.gtefcu.org> wrote in message
news:uRjuJUqMEHA.3292@.TK2MSFTNGP11.phx.gbl...
> The easiest way is to run them in Query Analyzer. Go to
> Tools/Options/Results and pick Results to File and Custom Delimiter. Then
> execute your proc.
Yes, I am doing that for testing. Now I want to automate it.
Does anyone know of a good way?
- Kristoffer -
|||You can also do all of the above mentioned by doing a simple export data
using the DTS Wizard. You can select your source to be your DB and the
Destination to be a text file. Use a SQL query at the source and just have
it execute your stored proc. you can set your custom delimiters you need
for the output file. You can save that as a DTS package and rerun it any
time.
OR
you could create another proc that just selects the # in between and use BCP
to pump out the data to text
http://msdn.microsoft.com/library/de...p_bcp_61et.asp
Jeff Duncan
MCDBA, MCSE+I
"Kristoffer Persson" <hidden> wrote in message
news:OVQ4%23hqMEHA.268@.TK2MSFTNGP11.phx.gbl...[vbcol=seagreen]
> "Jeff Duncan" <jduncan@.gtefcu.org> wrote in message
> news:uRjuJUqMEHA.3292@.TK2MSFTNGP11.phx.gbl...
Then
> Yes, I am doing that for testing. Now I want to automate it.
> Does anyone know of a good way?
> - Kristoffer -
>
|||I was thinking BCP would work, but it seems very complicated to use.
The DTS approach seems even better, if it works with MSDE. Does it?
That leaves only one question on the topic: How do I remove the empty rows
that appear between the returned recordsets?
Thank you!
- Kristoffer -
"Jeff Duncan" <jduncan@.gtefcu.org> wrote in message
news:eoPs4tqMEHA.4036@.TK2MSFTNGP12.phx.gbl...
> You can also do all of the above mentioned by doing a simple export data
> using the DTS Wizard.
> OR
> you could create another proc that just selects the # in between and use
BCP
> to pump out the data to text
>
http://msdn.microsoft.com/library/de...p_bcp_61et.asp
|||DTS Comes with SQL Server and not MSDE. However if you have a SQL Server
you can create a DTS package there and easily have your source be the MSDE
DB on the other box.
Jeff Duncan
MCDBA, MCSE+I
"Kristoffer Persson" <hidden> wrote in message
news:uxwoXzqMEHA.740@.TK2MSFTNGP12.phx.gbl...
> I was thinking BCP would work, but it seems very complicated to use.
> The DTS approach seems even better, if it works with MSDE. Does it?
> That leaves only one question on the topic: How do I remove the empty rows
> that appear between the returned recordsets?
> Thank you!
> - Kristoffer -
> "Jeff Duncan" <jduncan@.gtefcu.org> wrote in message
> news:eoPs4tqMEHA.4036@.TK2MSFTNGP12.phx.gbl...
> BCP
>
http://msdn.microsoft.com/library/de...p_bcp_61et.asp
>

Record set to file

Any tips on how to get a recordset into a file. I want the result of a stored procedure (multiple rows) written to a flat file. I've tried a data flow task with an OLE DB Source linked to Raw File destination but that produces gibberish in the file - I need the raw rows returned from the s/p

Any tips much appreciated.

Greg.You can use DTS (Data Transformation Service) to accomplish this.|||I understood SSIS was the new DTS. Any pointers on how I can go about this Mike?

Greg.
|||Yes, in v2005. I haven't used it extensively, but you can get the information on how to here: http://msdn2.microsoft.com/ms141823(en-US,SQL.90).aspx|||

What do you mean by raw rows? The raw dest produces a binary file that is for use by the dataflow. If you want a readable file then use the flat file destination, which will create a text file.

HTH,

Matt

|||Thanks guys. Got it figured out using the flat file destination.

Greg.

Record locking within a stored procedure

Hi
I'd like to be able to lock a record in a table, row locking, update some
fields, then release the lock when finished. I'd also like to be able to
attempt the row lock for a specified amount of time, if, for example, anothe
r
session is already locking this record. The session would only be locking th
e
record for a minute amount of time, however I need to ensure that no
conflicts occur.
If it helps, I'm running the stored procedures via VFP9 so I know a
reasonable amount of SQL syntax, parsing etc.
What's the SQL syntax to complete something like this?
RegardsG18LLO (G18LLO@.discussions.microsoft.com) writes:
> I'd like to be able to lock a record in a table, row locking, update
> some fields, then release the lock when finished. I'd also like to be
> able to attempt the row lock for a specified amount of time, if, for
> example, another session is already locking this record. The session
> would only be locking the record for a minute amount of time, however I
> need to ensure that no conflicts occur.
> If it helps, I'm running the stored procedures via VFP9 so I know a
> reasonable amount of SQL syntax, parsing etc.
> What's the SQL syntax to complete something like this?
There is not really explicit syntax for this. The locking that SQL Server
uses for it's purposes is not intended for application use, nor is it
suitable for it.
There are a couple of ways to go. One is to add a column to the table
saying that it is locked. Such a column should probably have some sort
of a time stamp, and some rules to tell whether the lock can considered
to still be valid or to be stale.
Another way is to use application locks. In this case you are using
the lock manager in SQL Server, but you are not interferring with SQL
Server's internal business. An application is lock on a named resource.
Assuming the the table is called Widgets and has a numeric id as its
primary key, you could create an application lock on the resource
"Widget16" to lock the row with WidgetId = 16.
One thing to consider here is that you should not run too long transactions.
For instance, if the record is locked, because a user is about to update
it, you should have a transaction while waiting for user input. This
does not rule out application lock, as they can be on session level.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||On Thu, 29 Dec 2005 11:03:07 -0800, G18LLO
<G18LLO@.discussions.microsoft.com> wrote:
>I'd like to be able to lock a record in a table, row locking, update some
>fields, then release the lock when finished. I'd also like to be able to
>attempt the row lock for a specified amount of time, if, for example, anoth
er
>session is already locking this record. The session would only be locking t
he
>record for a minute amount of time, however I need to ensure that no
>conflicts occur.
>If it helps, I'm running the stored procedures via VFP9 so I know a
>reasonable amount of SQL syntax, parsing etc.
>What's the SQL syntax to complete something like this?
It's politicallly incorrect to do this "pessimistic locking" in
SQLServer, although it is possible and works reasonably well, if you
know what you're doing.
Something like:
begin transaction
-- lock record from other writers, they can still read
select <anyfield> from <yourtable> with (updlock)
-- with modification and default isolation levels,
-- others will probably not be able to read, either
update <yourtable> set <fields>
commit transaction
-- now changes are made and record(s) unlocked
Actually, you may not even need the select, unless you want to lock in
advance of the update.
Also look at lock_timeout, if you play with pessimistic locking you're
going to need it!
Note that in SQLServer2005 it will become a little bit less
politically incorrect because of the new "look-aside" isolation level
(I forget the Microsoft name for it ...)
Good luck.
Josh|||Josh with all due respect, SQL Server will not block until there is an updat
e
that occurs in a database transaction. A select with holdlock or updlock,
will allow another user to also select the same data with or without a
holdlock or updlock. IMO, SQL Server shouldn't do that but it does.
If you want users to line up, single file in a queue, the following code
will cause it to happen.
begin transaction
--basically a bogus update by setting a column to itself
--this causes a lock on that row
--any other T-SQL code that tries to update the same row will wait in line
--effectively creating a queue
update MyControlTable
set <column> = <column>
where <condition>
<do your work>
commit transaction
If there is only one situation, MyControlTable can be a single column,
single row table. In my case, I had a multiple column, multipler row table
so I could block users based on company id and functional area. For example
,
company 1 and loading customer data to ensure two different people didn't tr
y
to run a data load of customer information for company 1 at the same time as
the program code and business rules did not support concurrent data loading.
Another example, a person could queue up the loading of sales data for
different periods without having to wait for one to finish before starting
the next one. SQL Server became the traffic cop.
NOTE: This does not address the waiting for a specified amount of time. You
should be able to use the connection's timeout property.
Just my two cents,
Joe
"jxstern" wrote:

> On Thu, 29 Dec 2005 11:03:07 -0800, G18LLO
> <G18LLO@.discussions.microsoft.com> wrote:
> It's politicallly incorrect to do this "pessimistic locking" in
> SQLServer, although it is possible and works reasonably well, if you
> know what you're doing.
> Something like:
> begin transaction
> -- lock record from other writers, they can still read
> select <anyfield> from <yourtable> with (updlock)
> -- with modification and default isolation levels,
> -- others will probably not be able to read, either
> update <yourtable> set <fields>
> commit transaction
> -- now changes are made and record(s) unlocked
> Actually, you may not even need the select, unless you want to lock in
> advance of the update.
> Also look at lock_timeout, if you play with pessimistic locking you're
> going to need it!
> Note that in SQLServer2005 it will become a little bit less
> politically incorrect because of the new "look-aside" isolation level
> (I forget the Microsoft name for it ...)
> Good luck.
> Josh
>|||Joe from WI (JoefromWI@.discussions.microsoft.com) writes:
> Josh with all due respect, SQL Server will not block until there is an
> update that occurs in a database transaction. A select with holdlock or
> updlock, will allow another user to also select the same data with or
> without a holdlock or updlock. IMO, SQL Server shouldn't do that but it
> does.
Then you have misunderstood the meaning of these hints.
HOLDLOCK simply means "use serializable isolation level". That is, ensure
that if I run this SELECT in the same transaction, that it will return
the same result. No rows modified, deleted or added.
UPDLOCK means "I am about to update this row". UPDLOCK is a shared lock,
in so far that it does not prevent other readers, but only one process
can have an UPDLOCK on a resource.

> If you want users to line up, single file in a queue, the following code
> will cause it to happen.
> begin transaction
> --basically a bogus update by setting a column to itself
> --this causes a lock on that row
> --any other T-SQL code that tries to update the same row will wait in line
> --effectively creating a queue
> update MyControlTable
> set <column> = <column>
> where <condition>
><do your work>
That is a poor solution. (Not the least since the DB engine may outsmart
you, and not take out a lock, since nothing was changed.) There are at least
two that are better.
One is to use the XLOCK hint to get an exclusive lock.
But the best in my opinion is to use application locks, as then you have
more control over the resources you lock.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||> One is to use the XLOCK hint to get an exclusive lock.
Just be careful with the XLOCK hint. There's an optimization where SQL Serve
r doesn't respect a row
level XLOCK if the row hasn't been modified since the earliest open transact
ion (or something to
that effect):
--Connection 1
USE pubs
BEGIN TRAN
SELECT *
FROM authors (xlock)
WHERE au_lname = 'White'
--Connection 2
USE pubs
EXEC sp_lock
SELECT *
FROM authors
WHERE au_lname = 'White'
--Query is not blocked
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
Blog: http://solidqualitylearning.com/blogs/tibor/
"Erland Sommarskog" <esquel@.sommarskog.se> wrote in message
news:Xns973E924F3F64Yazorman@.127.0.0.1...
> Joe from WI (JoefromWI@.discussions.microsoft.com) writes:
> Then you have misunderstood the meaning of these hints.
> HOLDLOCK simply means "use serializable isolation level". That is, ensure
> that if I run this SELECT in the same transaction, that it will return
> the same result. No rows modified, deleted or added.
> UPDLOCK means "I am about to update this row". UPDLOCK is a shared lock,
> in so far that it does not prevent other readers, but only one process
> can have an UPDLOCK on a resource.
>
> That is a poor solution. (Not the least since the DB engine may outsmart
> you, and not take out a lock, since nothing was changed.) There are at lea
st
> two that are better.
> One is to use the XLOCK hint to get an exclusive lock.
> But the best in my opinion is to use application locks, as then you have
> more control over the resources you lock.
>
> --
> Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
> Books Online for SQL Server 2005 at
> http://www.microsoft.com/technet/pr...oads/books.mspx
> Books Online for SQL Server 2000 at
> http://www.microsoft.com/sql/prodin...ions/books.mspx|||Tibor Karaszi (tibor_please.no.email_karaszi@.hotmail.nomail.com) writes:
> Just be careful with the XLOCK hint. There's an optimization where SQL
> Server doesn't respect a row level XLOCK if the row hasn't been modified
> since the earliest open transaction (or something to that effect):
> --Connection 1
> USE pubs
> BEGIN TRAN
> SELECT *
> FROM authors (xlock)
> WHERE au_lname = 'White'
>
> --Connection 2
> USE pubs
> EXEC sp_lock
> SELECT *
> FROM authors
> WHERE au_lname = 'White'
> --Query is not blocked
Thanks, Tibor.
Just stresses my point that you should use application locks for this
purpose.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||Please excuse my ignorance for locking hints but if you have two transaction
s
issuing a select with a xlock, updlock, or holdlock on the same row of data,
how can SQL Server guarntee that the transaction will be able to repeat the
read? The only combination that worked in my testing is the holdlock when
tran1 selected data with a holdlock, tran2 could select the data with a
holdlock but it could not update it until tran1 completed. If tran1 had a
updlock or xlock, tran2 was able to read and update the data ignoring tran1'
s
lock.
So I'd recommend having a datetime column so that there is a real update
just in case the optimizer gets too smart. ;) Optionally, add connection
information.
begin transaction
update MyControlTable
set LastLock = getdate(), SPID = @.@.SPID, Username = SYSTEM_USER,
ApplicationName = APP_NAME, Workstation = HOST_NAME ( ) , DBUser = USER_NAME
()
where <condition>
<do other work here>
commit transaction
Personally, I would NOT use an application lock such as updating a column on
the data row indicating that it is locked. Because sooner or later, there
will be an application error, dropped connection, or whatever and you're
stuck with a logical lock on the row. And using a datetime to deterimine
whether the lock is stale can be dangerous, in my opinion. How long do you
let other users wait--seconds? minutes? hours? days? Sooner or later,
someone will come along with a longer-than-expected job and the logical lock
s
become worthless.
With my solution, as soon as the connection drops one way or another the
lock is released automatically (either through a commit or a rollback) and
the next user has immediate access.
Just my two cents,
Joe
"Erland Sommarskog" wrote:

> Tibor Karaszi (tibor_please.no.email_karaszi@.hotmail.nomail.com) writes:
> Thanks, Tibor.
> Just stresses my point that you should use application locks for this
> purpose.
>
> --
> Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
> Books Online for SQL Server 2005 at
> http://www.microsoft.com/technet/pr...oads/books.mspx
> Books Online for SQL Server 2000 at
> http://www.microsoft.com/sql/prodin...ions/books.mspx
>|||See my post about XLOCK hint being essentially useless.
UPDLOCK work, but both connections need to use UPDLOCK. Update lock doesn't
block shared locks.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
Blog: http://solidqualitylearning.com/blogs/tibor/
"Joe from WI" <JoefromWI@.discussions.microsoft.com> wrote in message
news:6E32CDD2-ECB5-44F4-A2E6-249794010E06@.microsoft.com...
> Please excuse my ignorance for locking hints but if you have two transacti
ons
> issuing a select with a xlock, updlock, or holdlock on the same row of dat
a,
> how can SQL Server guarntee that the transaction will be able to repeat th
e
> read? The only combination that worked in my testing is the holdlock when
> tran1 selected data with a holdlock, tran2 could select the data with a
> holdlock but it could not update it until tran1 completed. If tran1 had a
> updlock or xlock, tran2 was able to read and update the data ignoring tran
1's
> lock.
> So I'd recommend having a datetime column so that there is a real update
> just in case the optimizer gets too smart. ;) Optionally, add connection
> information.
> begin transaction
> update MyControlTable
> set LastLock = getdate(), SPID = @.@.SPID, Username = SYSTEM_USER,
> ApplicationName = APP_NAME, Workstation = HOST_NAME ( ) , DBUser = USER_NA
ME()
> where <condition>
> <do other work here>
> commit transaction
> Personally, I would NOT use an application lock such as updating a column
on
> the data row indicating that it is locked. Because sooner or later, there
> will be an application error, dropped connection, or whatever and you're
> stuck with a logical lock on the row. And using a datetime to deterimine
> whether the lock is stale can be dangerous, in my opinion. How long do yo
u
> let other users wait--seconds? minutes? hours? days? Sooner or later,
> someone will come along with a longer-than-expected job and the logical lo
cks
> become worthless.
> With my solution, as soon as the connection drops one way or another the
> lock is released automatically (either through a commit or a rollback) and
> the next user has immediate access.
> Just my two cents,
> Joe
> "Erland Sommarskog" wrote:
>|||Joe from WI (JoefromWI@.discussions.microsoft.com) writes:
> Personally, I would NOT use an application lock such as updating a
> column on the data row indicating that it is locked. Because sooner or
> later, there will be an application error, dropped connection, or
> whatever and you're stuck with a logical lock on the row.
No, an application lock is handled by lock manager in SQL Server.
Application locks on either be on transaction level or session level.
Application locks on transaction level are releasd when the transaction
is committed or rolled back. Session-level locks are released when
the process disconnects. (There is a bug in SQL 2005 RTM, though, so
that a session application lock survives the reuse of a connnection
from the connection pool. I expect this bug to be fixed in SP1 of SQL 2005.
For more info, see sp_setapplock in Books Online.

> And using a datetime to deterimine whether the lock is stale can be
> dangerous, in my opinion. How long do you let other users
> wait--seconds? minutes? hours? days? Sooner or later, someone will come
> along with a longer-than-expected job and the logical locks become
> worthless.
Using a column to mark a row as lock is also a viable technique.
Particularly, this solution is necessary if the row is to be
locked while waiting for user input. Locking resources while waiting
for user input is simply admissible. What if user goes to lunch? Or
for holidays in two ws.
For how long to wait before such a lock is defined stale, is a
business decision, but maybe 30 minutes is reasonable. Of course
the application must be able to handle if the user presses Save after
40 minutes.
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx