Showing posts with label script. Show all posts
Showing posts with label script. Show all posts

Friday, March 30, 2012

Output Buffer Remove Row?

I am using a script component to create the output buffer dynamically. I use the Outputbuffer.AddRow() call. I then set all the fields I want, and its added to the output and later inserted into the database. If a field value fails it causes an error, but the record is partially inserted upto the point where the set field command caused the error. So if I set 10 fields, and it fails on field 5 it inserts data for the 5 fields that worked and nulls into the others.

As a result I have a try catch clause, and if it fails I want to cancell the addition of the new row. Is there a command like RemoveRow(), rollback, etc that can be used to not insert the record in error?

Sample code..

Try

PaymentOutputBuffer.AddRow()

PaymentOutputBuffer.Sequence = pi + 1

PaymentOutputBuffer.RecordID = Row.RecordID

PaymentOutputBuffer.PaymentMethod = PaymentArray(pi)

Catch e As Exception

PaymentErrorOutputBuffer.removecurrentrow(?)

End Try

Can you provide more of your script? Maybe even all of it?|||

The script is very long. I do the same basic task in three scripts for three different feeds, this is the shortest one. The only difference (basically) between this and the others is the number of field in the outputbuffer. Ok.. Here is the code:

Imports System

Imports System.Data

Imports System.Math

Imports Microsoft.SqlServer.Dts.Pipeline.Wrapper

Imports Microsoft.SqlServer.Dts.Runtime.Wrapper

Imports System.Text

Imports Company.SSIS.Functions

Public Class ScriptMain

Inherits UserComponent

Public Overrides Sub Input0_ProcessInputRow(ByVal Row As Input0Buffer)

Dim PaymentRecord As String = System.Text.Encoding.Unicode.GetString(Row.PaymentMethods.GetBlobData(0, CInt(Row.PaymentMethods.Length)))

Dim PaymentArray() As String

Dim pi As Integer

PaymentArray = Parse.StringParse(PaymentRecord, "\|")

For pi = 0 To PaymentArray.Length - 1

If PaymentArray(pi) <> "" Then

Try

PaymentOutputBuffer.AddRow()

PaymentOutputBuffer.Sequence = pi + 1

PaymentOutputBuffer.ServiceRecordID = Row.ServiceRecordID

PaymentOutputBuffer.PaymentMethod = PaymentArray(pi)

Catch e As Exception

PaymentErrorOutputBuffer.AddRow()

PaymentErrorOutputBuffer.ErrorRecordID = Row.ServiceRecordID

PaymentErrorOutputBuffer.ErrorCode = e.Message

PaymentErrorOutputBuffer.ErrorData.AddBlobData(Encoding.UTF8.GetBytes(PaymentArray(pi)))

End Try

End If

Next

End Sub

End Class

The Company.SSIS.Functions import is a dll I wrote. It has the Parse.StringParse(PaymentRecord, "\|") call. It is simply a regex function. I listed it below.. but basically splits the delimited field into multiple rows. So the goal is that it is called per row, splits the data in the row into an array and stores it as records. If the paymentmethod store fails, the record still gets inserted into the datase with the sequence and service record id. The catch directs creates a second output, that i then store to my error table. I essentially want the catch to still send to my error table, but for the first output not to be created if it fails and enters the catch.

Public Class Parse

Public Shared Function StringParse(ByVal StringValue As String, ByVal ParseValue As String) As String()

If Replace(StringValue, "", Nothing) Is Nothing Then

Return Split(StringValue)

Else

Dim pattern As String = ParseValue & "(?=(?:[^""]*""[^""]*"")*(?![^""]*""))"

Dim r As RegularExpressions.Regex = New RegularExpressions.Regex(pattern)

Return r.Split(StringValue)

End If

End Function

End Class

|||What are some of the reasons why the assignment to PaymentMethod could fail?|||

Payment method is varchar(20) field. The output is defined as String 20. Primary reason of failure is text truncation. On other code it may be bad date/time stamp, non integer value, etc. Typically it is a data error.

I can do a specific check on payment method to make sure its not in error before calling the addrow() so that the output is not called unless it will succeed. But for scenarios I don't think of, or conditions where I need to check 20+ fields this is not as practical. So I was hoping to use a try/catch process to insert the row if its good, otherwise write to the error table.

|||Yep, I hear ya... I just wanted you to think about performing data validation up front, and you have. Good.

Some of the other code experts may have to chime in now. |||Remove the current row with the call to the PipelineBuffer.RemoveRow() method. The script component does not expose the PipelineBuffer.RemoveRow() method directly, but its does expose the PipelineBuffer(s) in PrimeOutput, on which RemoveRow can be called.

Taking your scenario as example, save the underlying pipeline buffers, and call any PipelineBuffer method on them, including RemoveRow.

Imports System

Imports

Microsoft.SqlServer.Dts.Pipeline

Public Class ScriptMain

Inherits

UserComponent

Private

normalBuffer As PipelineBuffer

Private

errorBuffer As PipelineBuffer

Public Overrides Sub

Input0_ProcessInputRow _

(ByVal

Row As Input0Buffer)

Try

With

PaymentOutputBuffer

.AddRow()

.FirstString =

Row.GeneratedStr1

End

With

Catch

ex As Exception

With

PaymentErrorOutputBuffer

.AddRow()

.ErrorMessage =

ex.Message.Substring(0, _

Math.Min(ex.Message.Length,

250))

End

With

normalBuffer.RemoveRow()

' Remove

the row from normal, as normalBuffer

' is the

underlying PipelineBuffer

' for

PaymentOutputBuffer

End Try

End Sub

Public Overrides Sub

PrimeOutput(ByVal Outputs As Integer, _

ByVal

OutputIDs() As Integer,

_

ByVal

Buffers() As

Microsoft.SqlServer.Dts.Pipeline.PipelineBuffer)

' save

underlying PipelineBuffer to allow for calls to

'

PipelineBuffer methods

normalBuffer = Buffers(0)

errorBuffer = Buffers(1)

MyBase.PrimeOutput(Outputs,

OutputIDs, Buffers)

End Sub

End Class

|||Thanks.. .that works and does what I need. I was curious about the Buffers(x) value and if there is another way to set it to the specific outputbuffer. I tried to look at the help on the Pipeline buffer, but was not able to determine it. I want to be able to reference the Buffers(PaymentOutputBuffer) vs. a 0 so that if people add additional buffers, etc it will not break. Is there a way to make this go off the actual buffer name?|||Yes, the buffers can be referenced by name.

The OutputIDs array parameter to PrimeOutput has the integer buffer ids (not the offset) in coordinated order with the Buffers array.

The buffer's name is available via a call to ComponentMetaData.OutputCollection.FindObjectById(<id from OutputIds here>).Name.

See the following BOL reference for the OutputCollection methods: ms-help://MS.VSCC.v80/MS.VSIPCC.v80/MS.SQLSVR.v9.en/dtsref9mref/html/T_Microsoft_SqlServer_Dts_Pipeline_Wrapper_IDTSOutputCollection90_Members.htmsql

Output Buffer Remove Row?

I am using a script component to create the output buffer dynamically. I use the Outputbuffer.AddRow() call. I then set all the fields I want, and its added to the output and later inserted into the database. If a field value fails it causes an error, but the record is partially inserted upto the point where the set field command caused the error. So if I set 10 fields, and it fails on field 5 it inserts data for the 5 fields that worked and nulls into the others.

As a result I have a try catch clause, and if it fails I want to cancell the addition of the new row. Is there a command like RemoveRow(), rollback, etc that can be used to not insert the record in error?

Sample code..

Try

PaymentOutputBuffer.AddRow()

PaymentOutputBuffer.Sequence = pi + 1

PaymentOutputBuffer.RecordID = Row.RecordID

PaymentOutputBuffer.PaymentMethod = PaymentArray(pi)

Catch e As Exception

PaymentErrorOutputBuffer.removecurrentrow(?)

End Try

Can you provide more of your script? Maybe even all of it?|||

The script is very long. I do the same basic task in three scripts for three different feeds, this is the shortest one. The only difference (basically) between this and the others is the number of field in the outputbuffer. Ok.. Here is the code:

Imports System

Imports System.Data

Imports System.Math

Imports Microsoft.SqlServer.Dts.Pipeline.Wrapper

Imports Microsoft.SqlServer.Dts.Runtime.Wrapper

Imports System.Text

Imports Company.SSIS.Functions

Public Class ScriptMain

Inherits UserComponent

Public Overrides Sub Input0_ProcessInputRow(ByVal Row As Input0Buffer)

Dim PaymentRecord As String = System.Text.Encoding.Unicode.GetString(Row.PaymentMethods.GetBlobData(0, CInt(Row.PaymentMethods.Length)))

Dim PaymentArray() As String

Dim pi As Integer

PaymentArray = Parse.StringParse(PaymentRecord, "\|")

For pi = 0 To PaymentArray.Length - 1

If PaymentArray(pi) <> "" Then

Try

PaymentOutputBuffer.AddRow()

PaymentOutputBuffer.Sequence = pi + 1

PaymentOutputBuffer.ServiceRecordID = Row.ServiceRecordID

PaymentOutputBuffer.PaymentMethod = PaymentArray(pi)

Catch e As Exception

PaymentErrorOutputBuffer.AddRow()

PaymentErrorOutputBuffer.ErrorRecordID = Row.ServiceRecordID

PaymentErrorOutputBuffer.ErrorCode = e.Message

PaymentErrorOutputBuffer.ErrorData.AddBlobData(Encoding.UTF8.GetBytes(PaymentArray(pi)))

End Try

End If

Next

End Sub

End Class

The Company.SSIS.Functions import is a dll I wrote. It has the Parse.StringParse(PaymentRecord, "\|") call. It is simply a regex function. I listed it below.. but basically splits the delimited field into multiple rows. So the goal is that it is called per row, splits the data in the row into an array and stores it as records. If the paymentmethod store fails, the record still gets inserted into the datase with the sequence and service record id. The catch directs creates a second output, that i then store to my error table. I essentially want the catch to still send to my error table, but for the first output not to be created if it fails and enters the catch.

Public Class Parse

Public Shared Function StringParse(ByVal StringValue As String, ByVal ParseValue As String) As String()

If Replace(StringValue, "", Nothing) Is Nothing Then

Return Split(StringValue)

Else

Dim pattern As String = ParseValue & "(?=(?:[^""]*""[^""]*"")*(?![^""]*""))"

Dim r As RegularExpressions.Regex = New RegularExpressions.Regex(pattern)

Return r.Split(StringValue)

End If

End Function

End Class

|||What are some of the reasons why the assignment to PaymentMethod could fail?|||

Payment method is varchar(20) field. The output is defined as String 20. Primary reason of failure is text truncation. On other code it may be bad date/time stamp, non integer value, etc. Typically it is a data error.

I can do a specific check on payment method to make sure its not in error before calling the addrow() so that the output is not called unless it will succeed. But for scenarios I don't think of, or conditions where I need to check 20+ fields this is not as practical. So I was hoping to use a try/catch process to insert the row if its good, otherwise write to the error table.

|||Yep, I hear ya... I just wanted you to think about performing data validation up front, and you have. Good.

Some of the other code experts may have to chime in now. |||Remove the current row with the call to the PipelineBuffer.RemoveRow() method. The script component does not expose the PipelineBuffer.RemoveRow() method directly, but its does expose the PipelineBuffer(s) in PrimeOutput, on which RemoveRow can be called.

Taking your scenario as example, save the underlying pipeline buffers, and call any PipelineBuffer method on them, including RemoveRow.

Imports System

Imports

Microsoft.SqlServer.Dts.Pipeline

Public Class ScriptMain

Inherits

UserComponent

Private

normalBuffer As PipelineBuffer

Private

errorBuffer As PipelineBuffer

Public Overrides Sub

Input0_ProcessInputRow _

(ByVal

Row As Input0Buffer)

Try

With

PaymentOutputBuffer

.AddRow()

.FirstString =

Row.GeneratedStr1

End

With

Catch

ex As Exception

With

PaymentErrorOutputBuffer

.AddRow()

.ErrorMessage =

ex.Message.Substring(0, _

Math.Min(ex.Message.Length,

250))

End

With

normalBuffer.RemoveRow()

' Remove

the row from normal, as normalBuffer

' is the

underlying PipelineBuffer

' for

PaymentOutputBuffer

End Try

End Sub

Public Overrides Sub

PrimeOutput(ByVal Outputs As Integer, _

ByVal

OutputIDs() As Integer,

_

ByVal

Buffers() As

Microsoft.SqlServer.Dts.Pipeline.PipelineBuffer)

' save

underlying PipelineBuffer to allow for calls to

'

PipelineBuffer methods

normalBuffer = Buffers(0)

errorBuffer = Buffers(1)

MyBase.PrimeOutput(Outputs,

OutputIDs, Buffers)

End Sub

End Class

|||Thanks.. .that works and does what I need. I was curious about the Buffers(x) value and if there is another way to set it to the specific outputbuffer. I tried to look at the help on the Pipeline buffer, but was not able to determine it. I want to be able to reference the Buffers(PaymentOutputBuffer) vs. a 0 so that if people add additional buffers, etc it will not break. Is there a way to make this go off the actual buffer name?|||Yes, the buffers can be referenced by name.

The OutputIDs array parameter to PrimeOutput has the integer buffer ids (not the offset) in coordinated order with the Buffers array.

The buffer's name is available via a call to ComponentMetaData.OutputCollection.FindObjectById(<id from OutputIds here>).Name.

See the following BOL reference for the OutputCollection methods: ms-help://MS.VSCC.v80/MS.VSIPCC.v80/MS.SQLSVR.v9.en/dtsref9mref/html/T_Microsoft_SqlServer_Dts_Pipeline_Wrapper_IDTSOutputCollection90_Members.htm

Tuesday, March 20, 2012

Other Generate Script problems in SQL Server Management Studio

Why have often used scripting settings been removed from SQL Server 2005:

Issues associated with Scripting options:

Query Analyzer allowed the following generic options that have been removed from SSMS:
Identifier Delimiter : None, Version dependent, [] or ""
Do not script the collation.
Generate Transact-SQL to remove referenced component. Script tests for existence prior to attempt to remove component.
Do not include 'ON <filegroup>' clause directing filegroup use.
and table Scripting Options:
Qualify object name by its owner.
Do not include definition of identity property, seed, and increment.
Generate SET ANSI_PADDING ON and SET ANSI_PADDING OFF statements before CREATE TABLE statements.

Also Enterprise Manager Generate SQL Scripts tool had:
Files to Generate: Create one file or one file per object - Gone!
Create Drop object options - now it's one or the other.

As

someone else said in another post - why have Microsoft removed useful functionality

from the scripting options. It doesn't make sense - were these options

over looked or was it a conscious decision.

When will these

settings be reinstated - (and they need to be able to be set for the

whole IDE as well as in the wizard (as per Query Analyzer:Tools|Options

)

3rd Party Scripter for me until this is fixed - damn just need to find one now!

Alex

Hi Alex,

Some of these you will see addressed in SP2 -- Such as Create Drop options.

The others are in backlog of work items for the next general release of SQL Server.

A partial - (as in brief) explanation for why some disappeared had to do with 'forward' compatibility.

I will log your input in our Team Server database if you don't mind.

Thanks,

Terrence Nevins

SQL Server Program Manager

Other Generate Script problems in SQL Server Management Studio

Why have often used scripting settings been removed from SQL Server 2005:

Issues associated with Scripting options:

Query Analyzer allowed the following generic options that have been removed from SSMS:
Identifier Delimiter : None, Version dependent, [] or ""
Do not script the collation.
Generate Transact-SQL to remove referenced component. Script tests for existence prior to attempt to remove component.
Do not include 'ON <filegroup>' clause directing filegroup use.
and table Scripting Options:
Qualify object name by its owner.
Do not include definition of identity property, seed, and increment.
Generate SET ANSI_PADDING ON and SET ANSI_PADDING OFF statements before CREATE TABLE statements.

Also Enterprise Manager Generate SQL Scripts tool had:
Files to Generate: Create one file or one file per object - Gone!
Create Drop object options - now it's one or the other.

As someone else said in another post - why have Microsoft removed useful functionality from the scripting options. It doesn't make sense - were these options over looked or was it a conscious decision.

When will these settings be reinstated - (and they need to be able to be set for the whole IDE as well as in the wizard (as per Query Analyzer:Tools|Options )

3rd Party Scripter for me until this is fixed - damn just need to find one now!

Alex

Hi Alex,

Some of these you will see addressed in SP2 -- Such as Create Drop options.

The others are in backlog of work items for the next general release of SQL Server.

A partial - (as in brief) explanation for why some disappeared had to do with 'forward' compatibility.

I will log your input in our Team Server database if you don't mind.

Thanks,

Terrence Nevins

SQL Server Program Manager

Otain error details from a DTS package through T-SQL. Was(xp_sendmail on script

SQL Server 2000

Good day all,

I've been asked to create a DTS package that will execute 2 other DTS packages (yeah, I know... personally I want to write a sp for it *shrug*) and send an e-mail out reporting a failure and failure details.

So I have a couple of questions for you;

How do I pick up the error number (and description?) from a failed DTS and pass it to my sendmail task?
Is it possible to send anything other than plain text e-mails?
Can I change the e-mail priority to "high"?

I appreciate any help you can offer me :)USE master
GO

IF EXISTS (SELECT 1 FROM sysobjects WHERE type = 'S' AND name = 'sp_dtsFailureEmail') BEGIN
DROP PROCEDURE sp_dtsFailureEmail
END
GO

CREATE PROCEDURE sp_dtsFailureEmail
@.dtsName varchar(64)
, @.errorNumber int = 0
AS

IF @.errorNumber <> 0 BEGIN
DECLARE @.message varchar(2000)
, @.subject varchar(255)
, @.errorDesc nvarchar(255)

SET @.errorDesc = (SELECT description FROM sysmessages WHERE error = @.errorNumber)
SET @.subject = '***DTS FAILURE*** ' + @.dtsname + ' ***DTS FAILURE***'
SET @.message = 'DTS Package:' + Char(9) + Char(9) + @.dtsName
+ Char(13) + 'Failure Date:' + Char(9) + Char(9) + Convert(varchar, GetDate(), 0)
+ Char(13) + 'Error Number:' + Char(9) + Char(9) + Convert(varchar, @.errorNumber)
+ Char(13) + 'Error Description:' + Char(9) + @.errorDesc

PRINT ''
PRINT @.subject
PRINT ''
PRINT @.message
PRINT ''

EXEC xp_sendmail
@.recipients = '<enter your e-mail address>'
, @.subject = @.subject
, @.message = @.message
END
ELSE BEGIN
PRINT 'No Error'
END
GO

SELECT 1/0

EXEC sp_dtsFailureEmail '<enter dtsName>', @.@.Error

DROP PROCEDURE sp_dtsFailureEmail

I'm getting close, but I still don't know how to pass the error number from a DTS to... anywhere!!|||EXEC xp_cmdshell 'DTSRun /S "SQL-XXXX-XXXXX" /N "<dtsname>" /G "{5A14F80F-8EE2-477D-BE95-DC90A343D2A3}" /W "0" /E '
SELECT @.@.Error

Returns no error number when the DTS fails... So this suggests that this cannot be done!
Any ideas?|||As you know I know stuff all about DTS but you are not getting much help here.

1) Should you change the title of the thread? The problem does not really have anything to do with xp_sendmail.
2) Have you tried:

Declare @.error_return AS INT
EXEC @.error_return = xp_cmdshell 'DTSRun /S "SQL-XXXX-XXXXX" /N "<dtsname>" /G "{5A14F80F-8EE2-477D-BE95-DC90A343D2A3}" /W "0" /E '
SELECT @.error_return ??
3) Have you considered setting up a global variable, trapping the error in the DTS script and setting the global. Then test the global when the DTS script has finished.

HTH|||1) Wilco... my q2&3 were sp_sendmail though..

2) I'm just working on that! It returns a bit value declaring whether there was an error or not.

3) Never used global variables in DTS before - will look up if I run into a dead end with point 2.

Here's my current working code.

USE master
GO

IF EXISTS (SELECT 1 FROM sysobjects WHERE type = 'S' AND name = 'sp_dtsFailureEmail') BEGIN
DROP PROCEDURE sp_dtsFailureEmail
END
GO

CREATE PROCEDURE sp_dtsFailureEmail
@.dtsName varchar(64)
AS

DECLARE @.message varchar(8000)
, @.subject varchar(255)
, @.errorDesc nvarchar(255)

-- SET @.errorDesc = (SELECT description FROM sysmessages WHERE error = @.errorNumber)
SET @.subject = '***DTS FAILURE*** ' + @.dtsname + ' ***DTS FAILURE***'
SET @.message = 'DTS Package:' + Char(9) + Char(9) + @.dtsName
+ Char(13) + 'Failure Date:' + Char(9) + Char(9) + Convert(varchar, GetDate(), 0)
-- + Char(13) + 'Error Number:' + Char(9) + Char(9) + Convert(varchar, @.errorNumber)
-- + Char(13) + 'Error Description:' + Char(9) + @.errorDesc

PRINT ''
PRINT @.subject
PRINT ''
PRINT @.message
PRINT ''

-- EXEC xp_sendmail
-- @.recipients = '<enter your email>'
-- , @.subject = @.subject
-- , @.message = @.message
-- END
GO

DECLARE @.err bit
DECLARE @.dts varchar(64)
DECLARE @.cmd varchar(1024)

SET @.dts = 'test'
SET @.cmd = 'DTSRun /S "SQL-LIVE-IT038" /N "' + @.dts + '" /W "0" /E'

EXEC @.err = xp_cmdshell @.cmd
IF @.err <> 0 BEGIN
EXEC sp_dtsFailureEmail @.dts
END

DROP PROCEDURE sp_dtsFailureEmail

Returns:

DTSRun: Loading...
DTSRun: Executing...
DTSRun OnStart: DTSStep_DTSExecuteSQLTask_1
DTSRun OnError: DTSStep_DTSExecuteSQLTask_1, Error = -2147217900 (80040E14)
Error string: Divide by zero error encountered.
Error source: Microsoft OLE DB Provider for SQL Server
Help file:
Help context: 0

Error Detail Records:

Error: -2147217900 (80040E14); Provider Error: 8134 (1FC6)
Error string: Divide by zero error encountered.
Error source: Microsoft OLE DB Provider for SQL Server
Help file:
Help context: 0

DTSRun OnFinish: DTSStep_DTSExecuteSQLTask_1
DTSRun: Package execution complete.
NULL

***DTS FAILURE*** test ***DTS FAILURE***

DTS Package: test
Failure Date: Sep 5 2007 12:16PM

This raises another question: Is it possible to retrieve the output information from xp_cmdshell?|||This raises another question: Is it possible to retrieve the output information from xp_cmdshell?You mean stuff printed to the window? No.

How come? Are you hoping to get the details?

As said I don't know DTS but can you get the details within the package? If so then you can write all this to a table and check that.|||You mean stuff printed to the window?

Yep.

How come? Are you hoping to get the details?

Yep.

Basically the aim is to e-mail a group of users with the error details of a DTS package. But I'm startign to think it's more trouble than it's worth ;)|||GeorgeV on DTS: Basically the aim is to e-mail a group of users with the error details of a DTS package. But I'm startign to think it's more trouble than it's worth ;)

Strong candidate for my new sig ;)

That, for me, is DTS through and through.|||Yeeeeappp...
I'd love to rewrite the whole script in T-SQL; but can't...

I don't know how to do absolutely everything the DTS does
It's classed as a "major change" and I really cba going through all that just to do it.

A colleague of mine wrote a couple of hefty SSIS packages a while back which took a few CSV's from a 3rd party product and transformed them into our databases... All was fine until the column order changed on the CSV file. So even SSIS does the simplest of jobs badly.|||A colleague of mine wrote a couple of hefty SSIS packages a while back which took a few CSV's from a 3rd party product and transformed them into our databases... All was fine until the column order changed on the CSV file. So even SSIS does the simplest of jobs badly.To be fair unless you write bullet proof dynamic sql or have some sort of config file T-SQL will fair no better. I imagine Pat would start muttering something about "contracts" upon reading this. You change the contract between two systems and you can't really expect things to run smoothly.|||Actually, to resolve this an interim DTS package was created which produces a "clean" file. DTS packages remember the mapping.

The 3rd party product cost a total of $99 - we got what we paid for :p

Monday, March 12, 2012

osql with script trouble...

I have a sql file that contains:
if EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name ='newShopcart')
DROP DATABASE [newShopcart];
CREATE DATABASE [newShopcart] ON (NAME ='newShopcart_dat', FILENAME ='C:\MSSQL7\DATA\newShopcart.mdf' , SIZE = 10, FILEGROWTH =
10%) LOG ON (NAME ='newShopcart_log', FILENAME ='C:\MSSQL7\DATA\newShopcart.ldf' , SIZE = 10, FILEGROWTH = 10%);
USE [newShopcart];
GO
And I call this using osql in this way:
osql -D TLC -U sa -P thepassword -i MakeDB.sql -o MakeDB.log -n
I get the following in the resulting log:
Msg 2812, Level 16, State 62, Line 1
Could not find stored procedure 'i'.
I've noticed that changing the first line to USE [master] changes the log to:
Msg 2812, Level 16, State 62, Line 1
Could not find stored procedure 'U'.
This leads me to believe that it sees the first character of the file as the name of a Stored Procedure.
Any idea how to get around this?
Thanks in advance.
Mandy wrote:
> I have a sql file that contains:
> if EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name
> ='newShopcart')
> DROP DATABASE [newShopcart];
> CREATE DATABASE [newShopcart] ON (NAME ='newShopcart_dat', FILENAME
> ='C:\MSSQL7\DATA\newShopcart.mdf' , SIZE = 10, FILEGROWTH = 10%) LOG
> ON (NAME ='newShopcart_log', FILENAME
> ='C:\MSSQL7\DATA\newShopcart.ldf' , SIZE = 10, FILEGROWTH = 10%);
> USE [newShopcart];
> GO
> And I call this using osql in this way:
> osql -D TLC -U sa -P thepassword -i MakeDB.sql -o MakeDB.log -n
> I get the following in the resulting log:
> Msg 2812, Level 16, State 62, Line 1
> Could not find stored procedure 'i'.
> I've noticed that changing the first line to USE [master] changes the
> log to:
> Msg 2812, Level 16, State 62, Line 1
> Could not find stored procedure 'U'.
> This leads me to believe that it sees the first character of the file
> as the name of a Stored Procedure.
> Any idea how to get around this?
> Thanks in advance.
Does this code work from Query Analyzer? I see on your last line you
are using a semi-colon and a go. Does OSQL understand "go"? What's the
"n" option for and do you need it?
David Gugick
Imceda Software
www.imceda.com
|||It does work under QA. -n removes line numbers from results.

> Does this code work from Query Analyzer? I see on your last line you
> are using a semi-colon and a go. Does OSQL understand "go"? What's the
> "n" option for and do you need it?
> --
> David Gugick
> Imceda Software
> www.imceda.com
>
|||Are you sure this is an odbc data source and not just a regular SQL Server
connection? What happens if you remove the -D option and value? You could
also try adding the option -e to echo the commands as they are read, for
troubleshooting.
HTH
Kalen Delaney
SQL Server MVP
www.SolidQualityLearning.com
"Mandy" <clafarge@.NOSPAMgraphiced.com> wrote in message
news:eAn4RG%232EHA.1192@.tk2msftngp13.phx.gbl...
>I have a sql file that contains:
> if EXISTS (SELECT name FROM master.dbo.sysdatabases WHERE name
> ='newShopcart')
> DROP DATABASE [newShopcart];
> CREATE DATABASE [newShopcart] ON (NAME ='newShopcart_dat', FILENAME
> ='C:\MSSQL7\DATA\newShopcart.mdf' , SIZE = 10, FILEGROWTH =
> 10%) LOG ON (NAME ='newShopcart_log', FILENAME
> ='C:\MSSQL7\DATA\newShopcart.ldf' , SIZE = 10, FILEGROWTH = 10%);
> USE [newShopcart];
> GO
> And I call this using osql in this way:
> osql -D TLC -U sa -P thepassword -i MakeDB.sql -o MakeDB.log -n
> I get the following in the resulting log:
> Msg 2812, Level 16, State 62, Line 1
> Could not find stored procedure 'i'.
> I've noticed that changing the first line to USE [master] changes the log
> to:
> Msg 2812, Level 16, State 62, Line 1
> Could not find stored procedure 'U'.
> This leads me to believe that it sees the first character of the file as
> the name of a Stored Procedure.
> Any idea how to get around this?
> Thanks in advance.
>
|||I changed to specifying -S and ip address. When I added -e, it shows only one line of output:
I
So it still appears to only see the first character of the file.
"Kalen Delaney" <replies@.public_newsgroups.com> wrote in message news:%23PyX8MA3EHA.1396@.tk2msftngp13.phx.gbl...
> Are you sure this is an odbc data source and not just a regular SQL Server
> connection? What happens if you remove the -D option and value? You could
> also try adding the option -e to echo the commands as they are read, for
> troubleshooting.
|||-S is usually followed by the server name.
What version of SQL Server? Are you running osql remotely or locally?
Can you verify the version of osql?
How did you create the .sql file?
HTH
Kalen Delaney
SQL Server MVP
www.SolidQualityLearning.com
"Mandy" <clafarge@.NOSPAMgraphiced.com> wrote in message
news:Ogr83FH3EHA.2312@.TK2MSFTNGP15.phx.gbl...
>I changed to specifying -S and ip address. When I added -e, it shows only
>one line of output:
> I
> So it still appears to only see the first character of the file.
>
> "Kalen Delaney" <replies@.public_newsgroups.com> wrote in message
> news:%23PyX8MA3EHA.1396@.tk2msftngp13.phx.gbl...
>
|||I tried -S with ip and also server name.
MSSQL Version 7
osql on my machine, Server on network
osql version 2000.80.194.0
created script by Right-click on existing DB in Enterrprise and "Generate SQL Script", then changing names as needed for new
database.
"Kalen Delaney" <replies@.public_newsgroups.com> wrote in message news:u0bXMoH3EHA.1300@.TK2MSFTNGP14.phx.gbl...
> -S is usually followed by the server name.
> What version of SQL Server? Are you running osql remotely or locally?
> Can you verify the version of osql?
> How did you create the .sql file?
> --
> HTH
> --
> Kalen Delaney
> SQL Server MVP
> www.SolidQualityLearning.com
>
> "Mandy" <clafarge@.NOSPAMgraphiced.com> wrote in message
> news:Ogr83FH3EHA.2312@.TK2MSFTNGP15.phx.gbl...
>
|||Mandy wrote:
> I tried -S with ip and also server name.
> MSSQL Version 7
> osql on my machine, Server on network
> osql version 2000.80.194.0
> created script by Right-click on existing DB in Enterrprise and
> "Generate SQL Script", then changing names as needed for new database.
>
You really should patch your client tools. You are running the retail
release of OSQL.EXE from years ago. Apply the latest SQL Server SP3a
service pack to your client PC.
Also, try running a very simple script like "Select * from sysobjects"
from a script file and see if that works.
David Gugick
Imceda Software
www.imceda.com
|||Thanks for the pointer...
When I changed to a Select, I get:
Msg 2812, Level 16, State 62, Line 1
Could not find stored procedure 'S'.
Is there any reason why it would only see the first character?
"David Gugick" <davidg-nospam@.imceda.com> wrote in message news:uBnghHJ3EHA.524@.TK2MSFTNGP09.phx.gbl...[vbcol=seagreen]
> Mandy wrote:
|||Mandy wrote:[vbcol=seagreen]
> Thanks for the pointer...
> When I changed to a Select, I get:
> Msg 2812, Level 16, State 62, Line 1
> Could not find stored procedure 'S'.
> Is there any reason why it would only see the first character?
>
> "David Gugick" <davidg-nospam@.imceda.com> wrote in message
> news:uBnghHJ3EHA.524@.TK2MSFTNGP09.phx.gbl...
What format are you saving the file in? Is it unicode? Maybe OSQL cannot
read unicode files and requires an ANSI formatted file.
David Gugick
Imceda Software
www.imceda.com

osql vs Query Analyzer

We have a script with code like this
use master
go
-- do some stuff here
if exists (select name from sysdatabases where name = 'db_name')
begin
use db_name
-- do some stuff
exec storedproc
end
this works fine with Query Analyzer.
With OSQL it creates problem in the line exec storedproc. It says that
the stored procedure is not found.
we call osql as follows
osql -S servername -U username -P Password -i sqlfilename
now if we add the database name to osql
osql -S servername -U username -P Password -i sqlfilename -d db_name
it works fine.
Why should it matter. After all we are using USE statement inside the
script correctly.
How does it work in Query Analyzer.
TIA.
That should work. Can you post code which we can run that displays this?
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
Blog: http://solidqualitylearning.com/blogs/tibor/
"Data Cruncher" <dcruncher4@.netscape.net> wrote in message
news:1120679914.292796.77430@.g44g2000cwa.googlegro ups.com...
> We have a script with code like this
> use master
> go
> -- do some stuff here
> if exists (select name from sysdatabases where name = 'db_name')
> begin
> use db_name
> -- do some stuff
> exec storedproc
> end
> this works fine with Query Analyzer.
> With OSQL it creates problem in the line exec storedproc. It says that
> the stored procedure is not found.
> we call osql as follows
> osql -S servername -U username -P Password -i sqlfilename
> now if we add the database name to osql
>
> osql -S servername -U username -P Password -i sqlfilename -d db_name
> it works fine.
> Why should it matter. After all we are using USE statement inside the
> script correctly.
> How does it work in Query Analyzer.
> TIA.
>
|||Hi
You may want to use three part naming for the procedure call.
John
"Data Cruncher" wrote:

> We have a script with code like this
> use master
> go
> -- do some stuff here
> if exists (select name from sysdatabases where name = 'db_name')
> begin
> use db_name
> -- do some stuff
> exec storedproc
> end
> this works fine with Query Analyzer.
> With OSQL it creates problem in the line exec storedproc. It says that
> the stored procedure is not found.
> we call osql as follows
> osql -S servername -U username -P Password -i sqlfilename
> now if we add the database name to osql
>
> osql -S servername -U username -P Password -i sqlfilename -d db_name
> it works fine.
> Why should it matter. After all we are using USE statement inside the
> script correctly.
> How does it work in Query Analyzer.
> TIA.
>

osql vs Query Analyzer

We have a script with code like this
use master
go
-- do some stuff here
if exists (select name from sysdatabases where name = 'db_name')
begin
use db_name
-- do some stuff
exec storedproc
end
this works fine with Query Analyzer.
With OSQL it creates problem in the line exec storedproc. It says that
the stored procedure is not found.
we call osql as follows
osql -S servername -U username -P Password -i sqlfilename
now if we add the database name to osql
osql -S servername -U username -P Password -i sqlfilename -d db_name
it works fine.
Why should it matter. After all we are using USE statement inside the
script correctly.
How does it work in Query Analyzer.
TIA.That should work. Can you post code which we can run that displays this?
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
Blog: http://solidqualitylearning.com/blogs/tibor/
"Data Cruncher" <dcruncher4@.netscape.net> wrote in message
news:1120679914.292796.77430@.g44g2000cwa.googlegroups.com...
> We have a script with code like this
> use master
> go
> -- do some stuff here
> if exists (select name from sysdatabases where name = 'db_name')
> begin
> use db_name
> -- do some stuff
> exec storedproc
> end
> this works fine with Query Analyzer.
> With OSQL it creates problem in the line exec storedproc. It says that
> the stored procedure is not found.
> we call osql as follows
> osql -S servername -U username -P Password -i sqlfilename
> now if we add the database name to osql
>
> osql -S servername -U username -P Password -i sqlfilename -d db_name
> it works fine.
> Why should it matter. After all we are using USE statement inside the
> script correctly.
> How does it work in Query Analyzer.
> TIA.
>|||Hi
You may want to use three part naming for the procedure call.
John
"Data Cruncher" wrote:

> We have a script with code like this
> use master
> go
> -- do some stuff here
> if exists (select name from sysdatabases where name = 'db_name')
> begin
> use db_name
> -- do some stuff
> exec storedproc
> end
> this works fine with Query Analyzer.
> With OSQL it creates problem in the line exec storedproc. It says that
> the stored procedure is not found.
> we call osql as follows
> osql -S servername -U username -P Password -i sqlfilename
> now if we add the database name to osql
>
> osql -S servername -U username -P Password -i sqlfilename -d db_name
> it works fine.
> Why should it matter. After all we are using USE statement inside the
> script correctly.
> How does it work in Query Analyzer.
> TIA.
>

osql vs Query Analyzer

We have a script with code like this
use master
go
-- do some stuff here
if exists (select name from sysdatabases where name = 'db_name')
begin
use db_name
-- do some stuff
exec storedproc
end
this works fine with Query Analyzer.
With OSQL it creates problem in the line exec storedproc. It says that
the stored procedure is not found.
we call osql as follows
osql -S servername -U username -P Password -i sqlfilename
now if we add the database name to osql
osql -S servername -U username -P Password -i sqlfilename -d db_name
it works fine.
Why should it matter. After all we are using USE statement inside the
script correctly.
How does it work in Query Analyzer.
TIA.That should work. Can you post code which we can run that displays this?
--
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
Blog: http://solidqualitylearning.com/blogs/tibor/
"Data Cruncher" <dcruncher4@.netscape.net> wrote in message
news:1120679914.292796.77430@.g44g2000cwa.googlegroups.com...
> We have a script with code like this
> use master
> go
> -- do some stuff here
> if exists (select name from sysdatabases where name = 'db_name')
> begin
> use db_name
> -- do some stuff
> exec storedproc
> end
> this works fine with Query Analyzer.
> With OSQL it creates problem in the line exec storedproc. It says that
> the stored procedure is not found.
> we call osql as follows
> osql -S servername -U username -P Password -i sqlfilename
> now if we add the database name to osql
>
> osql -S servername -U username -P Password -i sqlfilename -d db_name
> it works fine.
> Why should it matter. After all we are using USE statement inside the
> script correctly.
> How does it work in Query Analyzer.
> TIA.
>|||Hi
You may want to use three part naming for the procedure call.
John
"Data Cruncher" wrote:
> We have a script with code like this
> use master
> go
> -- do some stuff here
> if exists (select name from sysdatabases where name = 'db_name')
> begin
> use db_name
> -- do some stuff
> exec storedproc
> end
> this works fine with Query Analyzer.
> With OSQL it creates problem in the line exec storedproc. It says that
> the stored procedure is not found.
> we call osql as follows
> osql -S servername -U username -P Password -i sqlfilename
> now if we add the database name to osql
>
> osql -S servername -U username -P Password -i sqlfilename -d db_name
> it works fine.
> Why should it matter. After all we are using USE statement inside the
> script correctly.
> How does it work in Query Analyzer.
> TIA.
>

Friday, March 9, 2012

osql using :r and GO

I have a script that calls other scripts using :r. I am using osql to run th
e
script. I am getting an error that seems to indicate GO is not allowed in a
:r script, yet it is required to create a table and trigger in the same
script. How do I do this?
I have greatly simplified the scripts, and :r files must be used. Here are
the details:
File releaseA.sql:
:r code/releaseA1.SQL
File releaseA1.SQL
CREATE TABLE A1 (
LOG_ID BIGINT IDENTITY NOT NULL,
CTRL_INSERT_DT DATETIME DEFAULT GETDATE() NOT NULL,
CTRL_UPDATE_DT DATETIME DEFAULT GETDATE() NOT NULL
)
GO
CREATE TRIGGER A1_RBUI
ON A1 FOR INSERT, UPDATE
AS
BEGIN
UPDATE A1
SET CTRL_UPDATE_DT = GETDATE(),
CTRL_INSERT_DT = ISNULL(I.CTRL_INSERT_DT, GETDATE())
FROM INSERTED I
INNER JOIN A1
ON I.LOG_ID = A1.LOG_ID
END
GO
COMMAND:
osql -i releaseA.sql
OUTPUT:
Incorrect syntax near the keyword 'CREATE'.
Msg 111, Level 15, State 1, Server MIRAGE, Line 35
'CREATE TRIGGER' must be the first statement in a query batch
Msg 170, Level 15, State 1, Server MIRAGE, Line 49
Line 49: Incorrect syntax near 'GO'.Hi
The following will work!
File f.sql
:r F1.sql
GO
:r F2.sql
File F1.sql
CREATE TABLE A1 (
LOG_ID BIGINT IDENTITY NOT NULL,
CTRL_INSERT_DT DATETIME DEFAULT GETDATE() NOT NULL,
CTRL_UPDATE_DT DATETIME DEFAULT GETDATE() NOT NULL
)
File F2.sql
CREATE TRIGGER A1_RBUI ON A1 FOR INSERT, UPDATE
AS
BEGIN
IF @.@.ROWCOUNT = 0 RETURN
SET NOCOUNT ON
UPDATE A1
SET CTRL_UPDATE_DT = GETDATE(),
CTRL_INSERT_DT = ISNULL(I.CTRL_INSERT_DT, GETDATE())
FROM INSERTED I
INNER JOIN A1
ON I.LOG_ID = A1.LOG_ID
END
John
"Bevo" wrote:

> I have a script that calls other scripts using :r. I am using osql to run
the
> script. I am getting an error that seems to indicate GO is not allowed in
a
> :r script, yet it is required to create a table and trigger in the same
> script. How do I do this?
> I have greatly simplified the scripts, and :r files must be used. Here are
> the details:
> File releaseA.sql:
> :r code/releaseA1.SQL
>
> File releaseA1.SQL
> CREATE TABLE A1 (
> LOG_ID BIGINT IDENTITY NOT NULL,
> CTRL_INSERT_DT DATETIME DEFAULT GETDATE() NOT NULL,
> CTRL_UPDATE_DT DATETIME DEFAULT GETDATE() NOT NULL
> )
> GO
> CREATE TRIGGER A1_RBUI
> ON A1 FOR INSERT, UPDATE
> AS
> BEGIN
> UPDATE A1
> SET CTRL_UPDATE_DT = GETDATE(),
> CTRL_INSERT_DT = ISNULL(I.CTRL_INSERT_DT, GETDATE())
> FROM INSERTED I
> INNER JOIN A1
> ON I.LOG_ID = A1.LOG_ID
> END
> GO
> COMMAND:
> osql -i releaseA.sql
> OUTPUT:
> Incorrect syntax near the keyword 'CREATE'.
> Msg 111, Level 15, State 1, Server MIRAGE, Line 35
> 'CREATE TRIGGER' must be the first statement in a query batch
> Msg 170, Level 15, State 1, Server MIRAGE, Line 49
> Line 49: Incorrect syntax near 'GO'.|||Thank you for the solution John, yet I was hoping there would be another way
.
This approach would require a seperate file for each trigger. Considering ou
r
database may have at least one trigger on each of our 100+ tables, this
results in alot of trigger files...
"John Bell" wrote:
> Hi
> The following will work!
> File f.sql
> :r F1.sql
> GO
> :r F2.sql
>
> File F1.sql
> CREATE TABLE A1 (
> LOG_ID BIGINT IDENTITY NOT NULL,
> CTRL_INSERT_DT DATETIME DEFAULT GETDATE() NOT NULL,
> CTRL_UPDATE_DT DATETIME DEFAULT GETDATE() NOT NULL
> )
>
> File F2.sql
> CREATE TRIGGER A1_RBUI ON A1 FOR INSERT, UPDATE
> AS
> BEGIN
> IF @.@.ROWCOUNT = 0 RETURN
> SET NOCOUNT ON
> UPDATE A1
> SET CTRL_UPDATE_DT = GETDATE(),
> CTRL_INSERT_DT = ISNULL(I.CTRL_INSERT_DT, GETDATE())
> FROM INSERTED I
> INNER JOIN A1
> ON I.LOG_ID = A1.LOG_ID
> END
> John
>
> "Bevo" wrote:
>|||Hi
In general I would consider a trigger as a separate object to the table
anyhow, therefore they will be kept separately in version control. With
a decent file naming convention it is not difficult to know which
tables have triggers (something that you can not currently tell from
your files!), and the fact that are in different files make no
difference once you have a scripted build process.
John|||The file names provided were for demostrative purposes only.
Another limitation I have found is that osql will not allow nested :r files.
This is not allowed:
F1.sql
:r F2.sql
F2.sql
:r F2_1.sql
This limits the source directory structure to just one tier, so one cannot
group functionality into tiered directories.
"John Bell" wrote:

> Hi
> In general I would consider a trigger as a separate object to the table
> anyhow, therefore they will be kept separately in version control. With
> a decent file naming convention it is not difficult to know which
> tables have triggers (something that you can not currently tell from
> your files!), and the fact that are in different files make no
> difference once you have a scripted build process.
> John
>|||Hi
I think that you may be trying to make this overly complicated.
http://tinyurl.com/5299q
John

osql using :r and GO

I have a script that calls other scripts using :r. I am using osql to run th
e
script. I am getting an error that seems to indicate GO is not allowed in a
:r script, yet it is required to create a table and trigger in the same
script. How do I do this?
I have greatly simplified the scripts, and :r files must be used. Here are
the details:
File releaseA.sql:
:r code/releaseA1.SQL
File releaseA1.SQL
CREATE TABLE A1 (
LOG_ID BIGINT IDENTITY NOT NULL,
CTRL_INSERT_DT DATETIME DEFAULT GETDATE() NOT NULL,
CTRL_UPDATE_DT DATETIME DEFAULT GETDATE() NOT NULL
)
GO
CREATE TRIGGER A1_RBUI
ON A1 FOR INSERT, UPDATE
AS
BEGIN
UPDATE A1
SET CTRL_UPDATE_DT = GETDATE(),
CTRL_INSERT_DT = ISNULL(I.CTRL_INSERT_DT, GETDATE())
FROM INSERTED I
INNER JOIN A1
ON I.LOG_ID = A1.LOG_ID
END
GO
COMMAND:
osql -i releaseA.sql
OUTPUT:
Incorrect syntax near the keyword 'CREATE'.
Msg 111, Level 15, State 1, Server MIRAGE, Line 35
'CREATE TRIGGER' must be the first statement in a query batch
Msg 170, Level 15, State 1, Server MIRAGE, Line 49
Line 49: Incorrect syntax near 'GO'.As you have noticed, the GO cannot be included in the :r script, because the
osql tool does not try to examine or parse the contents of the file, but
sends it directly to SQL Server for parsing, and the SQL Server doesn't like
GO.
Normally, GO is caught by osql itself, and never makes it to the back end.
Do you have to do this from within an osql session? A file with embedded GO
can be specified as a command line parameter to osql.
If the scripts have to call other scripts, can those other scripts be
editted at all? Instead of having a script with :r, maybe the script could
call xp_cmdshell which would call osql with the embedded script as a
parameter.
HTH
--
Kalen Delaney
SQL Server MVP
www.SolidQualityLearning.com
"Bevo" <Bevo@.discussions.microsoft.com> wrote in message
news:B2348B52-4A37-4330-88E4-2837200E3036@.microsoft.com...
>I have a script that calls other scripts using :r. I am using osql to run
>the
> script. I am getting an error that seems to indicate GO is not allowed in
> a
> :r script, yet it is required to create a table and trigger in the same
> script. How do I do this?
> I have greatly simplified the scripts, and :r files must be used. Here are
> the details:
> File releaseA.sql:
> :r code/releaseA1.SQL
>
> File releaseA1.SQL
> CREATE TABLE A1 (
> LOG_ID BIGINT IDENTITY NOT NULL,
> CTRL_INSERT_DT DATETIME DEFAULT GETDATE() NOT NULL,
> CTRL_UPDATE_DT DATETIME DEFAULT GETDATE() NOT NULL
> )
> GO
> CREATE TRIGGER A1_RBUI
> ON A1 FOR INSERT, UPDATE
> AS
> BEGIN
> UPDATE A1
> SET CTRL_UPDATE_DT = GETDATE(),
> CTRL_INSERT_DT = ISNULL(I.CTRL_INSERT_DT, GETDATE())
> FROM INSERTED I
> INNER JOIN A1
> ON I.LOG_ID = A1.LOG_ID
> END
> GO
> COMMAND:
> osql -i releaseA.sql
> OUTPUT:
> Incorrect syntax near the keyword 'CREATE'.
> Msg 111, Level 15, State 1, Server MIRAGE, Line 35
> 'CREATE TRIGGER' must be the first statement in a query batch
> Msg 170, Level 15, State 1, Server MIRAGE, Line 49
> Line 49: Incorrect syntax near 'GO'.|||It seems :r files cannot be tiered, is this not allowed:
F1.sql
:r F2.sql
F2.sql
:r F2_1.sql
"Kalen Delaney" wrote:

> As you have noticed, the GO cannot be included in the :r script, because t
he
> osql tool does not try to examine or parse the contents of the file, but
> sends it directly to SQL Server for parsing, and the SQL Server doesn't li
ke
> GO.
> Normally, GO is caught by osql itself, and never makes it to the back end.
> Do you have to do this from within an osql session? A file with embedded G
O
> can be specified as a command line parameter to osql.
> If the scripts have to call other scripts, can those other scripts be
> editted at all? Instead of having a script with :r, maybe the script could
> call xp_cmdshell which would call osql with the embedded script as a
> parameter.
> --
> HTH
> --
> Kalen Delaney
> SQL Server MVP
> www.SolidQualityLearning.com
>
> "Bevo" <Bevo@.discussions.microsoft.com> wrote in message
> news:B2348B52-4A37-4330-88E4-2837200E3036@.microsoft.com...
>
>|||So use xp_cmdshell and don't use :r at all.
HTH
--
Kalen Delaney
SQL Server MVP
www.SolidQualityLearning.com
"Bevo" <Bevo@.discussions.microsoft.com> wrote in message
news:170F0DC1-B0B1-4183-8540-34509092778D@.microsoft.com...
> It seems :r files cannot be tiered, is this not allowed:
> F1.sql
> :r F2.sql
> F2.sql
> :r F2_1.sql
>
> "Kalen Delaney" wrote:
>

OSQL Unicode Insert of ^F (Hex 06) from Registry Multi-String Value is Duplicating in DB

I'm using a Unicode sql script imported using OSQL. One of the values
we are attempting to insert is a Registry Multi-String value by passing
a string to a stored procedure. These Multi-String values appear to be
delimited by a Hex 06 (^F) character. When I import this character,
embedded in a string preceeded by an N, i.e

N'something something2 something3'

I end up with TWO of this character in the db. I get :

something something2 something3

Any help figuring out why or how to fix this? We MUST use Unicode due
to extended character sets, so NOT using Unicode is NOT a solution.Seems to be an encoding issue. We are using SQLXML to retrieve the
data initially. That seems to be UTF-8 encoding the data which creates
an xml stream that contains an odd escape sequence. This escape
sequence is not then being translated into the correct unicode
representation in the insert scripts (which are created by transforming
the xml). We are going to try Unicode encoding on the SQLXmlCommand
object and setting the xml to encoding=UTF-16 to see what happens.

Osql Syntax Help

Dear friends,

I was trying to run this script from a dos batch file under win xp but it's not working. Please help with the syntax.
================================================== =======
OSQL -U sa -P samsde -S firebird /Q "RESTORE DATABASE NAVIMEX FROM DISK = 'C:\30704' WITH

REPLACE, MOVE'NAVIMEX_Data' TO 'C:\Program Files\Microsoft SQL

Server\MSSQL\Data\NAVIMEX_Data.MDF',MOVE 'NAVIMEX_Log' TO 'C:\Program Files\Microsoft SQL

Server\MSSQL\Data\NAVIMEX_LOG.LDF'" QUIT
================================================== ========

Please provide me with the correct syntax to be put in a 'restore.bat' file :rolleyes:

Thanks in advance.
HotBirdWhat errors are you getting? You can add "/o<filename>" or use command line redirection to capture all errors. And don't use QUIT unless your RESTORE was unsuccessful.|||make sure that you dont hit enter after "microsoft sql" in the path
try a shorter path
also i believe that when you issue a restore cmd from disk, you have to specify the file name
ex
from disk = 'c:\data\northwind.mdf'

to back up robert, what errors do you get?|||Dear Friends,

Thank you for your replies,

The script works but I'm facing a problem while trying to restore from a network drive or a remote path (\\xxx.xxx.xxx.xxx\mypath\filename)

can you help please?

Regards,

Samer Chaer :rolleyes:|||It's usually due to a lack of necessary permissions on behalf of the security context under which the process is invoked.

osql script

I have two Osql scripting questions for windows?
1. How can I get my OSQL script to output to a CVS file. Such as "select *
from itemtable"
2. How can I create a osql backup script to will name the backup filename
system_date.bck. This way I have a backup for each day by date.
Thanks
Dan
hi Dan,
Danny wrote:
> I have two Osql scripting questions for windows?
> 1. How can I get my OSQL script to output to a CVS file. Such as "select *
> from itemtable"
SET NOCOUNT ON;
USE pubs;
GO
DECLARE @.fullcmd varchar(1000);
DECLARE @.cmd varchar(1000);
SET @.cmd = 'SELECT * FROM pubs.dbo.authors';
SET @.fullcmd = 'osql -S(Local) -E -q "' + @.cmd + '" -o c:\authors.txt';
-- this will result in a tab delimited columns output..
EXEC master..xp_cmdshell @.fullcmd ;
-- but you can prepare a format file as required, see BOL
PRINT 'PREPARE a format file';
SET @.fullcmd = 'bcp pubs.dbo.authors format nul -c -f c:\f.txt -T'
--EXEC master..xp_cmdshell @.fullcmd ;
PRINT 'MANUALLY MODIFY THE format file setting the "," as column separator
instead of the tab char';
SET @.fullcmd = 'bcp "' + @.cmd + '" queryout "c:\bcpAuthors.txt" -f
c:\f.txt -T';
SELECT @.fullcmd;
EXEC master..xp_cmdshell @.fullcmd;

> 2. How can I create a osql backup script to will name the backup
> filename system_date.bck. This way I have a backup for each day by
> date.
DECLARE @.db sysname;
DECLARE @.dir varchar(500);
DECLARE @.file varchar(256);
SELECT @.db = 'pubs', @.dir = 'c:\', @.file = CONVERT(varchar(8), GETDATE(),
112) + '_' + @.db + '.bak';
DECLARE @.fullpath varchar(1000);
SET @.fullpath = @.dir + @.file;
SELECT @.fullpath;
BACKUP DATABASE @.db
TO DISK = @.fullpath
WITH INIT;
Andrea Montanari (Microsoft MVP - SQL Server)
http://www.asql.biz http://italy.mvps.org
DbaMgr2k ver 0.21.0 - DbaMgr ver 0.65.0 and further SQL Tools
-- remove DMO to reply

osql return to check backup success/failure

I am running an osql using input script which runs a database backup. Is
there a way I could get a return of 1 or 0, 0 being success and 1 being
error. I tried using -b option but it returns the entire details of failure
followed by the return number and if i use -o paramater I dont see any
result at all. Can anyone please suggest some solution to this. any help
will be greatly appreciated. Thanks
Message posted via http://www.webservertalk.comTry catching the error in the batch being executed with OSQL and use
RAISERROR to set the DOS variable ERRORLEVEL.
Example:
Create a batch file with the following instructions:
osql -S my_server -E -d master -Q "backup database northwind to blahblah if
@.@.error != 0 raiserror ('Error during backup.', 16, 127)"
echo %ERRORLEVEL%
Execute the batch file and you will see 50000 as the echo of the variable
ERRORLEVEL, because I am specifying a msg_str in RAISERROR. You can create
your own error msg using sp_addmessage.
AMB
"ishaan99 via webservertalk.com" wrote:

> I am running an osql using input script which runs a database backup. Is
> there a way I could get a return of 1 or 0, 0 being success and 1 being
> error. I tried using -b option but it returns the entire details of failur
e
> followed by the return number and if i use -o paramater I dont see any
> result at all. Can anyone please suggest some solution to this. any help
> will be greatly appreciated. Thanks
> --
> Message posted via http://www.webservertalk.com
>|||I forgot to mention that in order to set DOS variable ERRORLEVEL, using
RAISERROR, you have to specify state 127.
Error Handling in SQL Server – a Background
http://www.sommarskog.se/error-handling-I.html
Implementing Error Handling with Stored Procedures
http://www.sommarskog.se/error-handling-II.html
AMB
"Alejandro Mesa" wrote:
> Try catching the error in the batch being executed with OSQL and use
> RAISERROR to set the DOS variable ERRORLEVEL.
> Example:
> Create a batch file with the following instructions:
> osql -S my_server -E -d master -Q "backup database northwind to blahblah i
f
> @.@.error != 0 raiserror ('Error during backup.', 16, 127)"
> echo %ERRORLEVEL%
> Execute the batch file and you will see 50000 as the echo of the variable
> ERRORLEVEL, because I am specifying a msg_str in RAISERROR. You can create
> your own error msg using sp_addmessage.
>
> AMB
>
> "ishaan99 via webservertalk.com" wrote:
>|||Thanks so much. That helped and worked fine.
Message posted via http://www.webservertalk.com

OSQL restore Database

Hi

I need to do a restore similar to the Restore Database in SQL Enterprise Manager using OSQL. I created an app to do the OSQL Run script command and it works fine. Is this the best way to create a setup to restore the database? Any ideas please!!

Best Regards
PhilipI'd use a VBS script. Easier then a full application...|||Thanks

osql question

Re:
osql -i test.sql -e -b -r 1 > temp.log
I intend to use osql to submit a bunch of SQL scripts from
a batch file.
If the SQL script has an error, the message is logged with
a line number. But the echoed input does not have line
numbers. Instead, the SQL text is preceded by a line that
looks like:
1> 2> 3> 4> 5> 6> 7> 8> 9> 10> 11> 12> 13> 14> 15> 16> 17>
18> 19> 20> 21> 22> 23>
The above looks to me like the line numbers without the
text. The text is successfully echoed after that, but
with out line numbers.
Is there any way to get the text echoed to the log file
with line numbers?
Hi
I don't think you can do exactly what you want. -n will turn of the N>
prompts and -m can set the error level to display.
John
"Randy" <anonymous@.discussions.microsoft.com> wrote in message
news:1c7c801c4524c$36dbc0a0$a001280a@.phx.gbl...
> Re:
> osql -i test.sql -e -b -r 1 > temp.log
> I intend to use osql to submit a bunch of SQL scripts from
> a batch file.
> If the SQL script has an error, the message is logged with
> a line number. But the echoed input does not have line
> numbers. Instead, the SQL text is preceded by a line that
> looks like:
> 1> 2> 3> 4> 5> 6> 7> 8> 9> 10> 11> 12> 13> 14> 15> 16> 17>
> 18> 19> 20> 21> 22> 23>
> The above looks to me like the line numbers without the
> text. The text is successfully echoed after that, but
> with out line numbers.
> Is there any way to get the text echoed to the log file
> with line numbers?
>
>

OSQL Question

I created a sql script that transfers data from my test system to production adn vice versa. I would like to use OSQL and be able to pass parameters to the SQL script.

Example: param 1 = test; param 2 = production.

Can anyone tell me if this is possible and how to do it?

Thanks in advance for all the help.You can't directly pass parameters as part of the OSQL command-line utility, but you have several alternatives for solving your problem.

As stated in Winnet mag article :
OSQL won't let you pass in parameters, but you can use the sp_executesql stored procedure, which can process parameterized SQL. (For detailed information about sp_executesql, see SQL Server Books OnlineBOL.) The following example lets you pass parameters into a T-SQL command but doesn't completely address how to pass a parameter as part of an OSQL command-line session (remember that you must issue the OSQL command from a command prompt):

osql -E -MyServer -Q "EXECUTE sp_executesql N'SELECT *
FROM northwind..
orders WHERE OrderId = @.OrderId' ,N'@.OrderId int' ,@.OrderId = 10248"
Another solution relies on the power of Windows to handle the parameterization for you. For DBAs who aren't familiar with Windows-level command-file processing, a batch file is a text file that has a .bat extension. Windows treats batch files as executables that run in the Command Prompt environment. You can think of batch files as mini programs that Windows runs.

You can simply create a file called SQLVariableBatch.bat, and put the following text in it:

osql -E -MyServer -Q "SELECT *
FROM northwind..orders WHERE OrderId = %1"
From the directory where you saved the .bat file, issue the following command from a command prompt window:

SQLVariableBatch 10248
When running this command, Windows will replace the %1 in the SQLVariableBatch.bat file with what comes after the batch file's name in the command linein this case, 10248. This is a simple example of batch processing in Windows; to learn more about batch files, see the Windows Help files.

You can also use Windows Scripting Host (WSH) to manage the parameterization. Using WSH for scripting and batch processing is much more flexible and powerful than using simple Windows batch files. I'm not a WSH expert, so I don't include an example of this solution, but I wanted to note that the option exists. For information about using WSH, see the MSDN Web site for Windows Script at

http://msdn.microsoft.com/library/default.asp?url=/nhp/default.asp?contentid=28001169 .|||Thanks for your help. I will try your suggestions and see if I can figure it out.

OSQL performance slow vs ISQLW

I have a script to run against a SQL Server 2000 database Windows 2003 OS).
The script creates temp tables and then uses the manipulated data to update
the database.
The probelem is when I run the script in Query Analyzer it takes less then
10 minutes to execute. When run the same script using OSQL it takes over an
hour.
Has anyone seen anything like this? Any suggestions would be great.
Possibly different SET setting can affect things. Also, you could try SET NOCOUNT ON and see if it
makes any difference.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Wex" <Wex@.discussions.microsoft.com> wrote in message
news:1B68CD56-168D-419F-A01D-8FF310F2EC96@.microsoft.com...
>I have a script to run against a SQL Server 2000 database Windows 2003 OS).
> The script creates temp tables and then uses the manipulated data to update
> the database.
> The probelem is when I run the script in Query Analyzer it takes less then
> 10 minutes to execute. When run the same script using OSQL it takes over an
> hour.
> Has anyone seen anything like this? Any suggestions would be great.

OSQL performance slow vs ISQLW

I have a script to run against a SQL Server 2000 database Windows 2003 OS).
The script creates temp tables and then uses the manipulated data to update
the database.
The probelem is when I run the script in Query Analyzer it takes less then
10 minutes to execute. When run the same script using OSQL it takes over an
hour.
Has anyone seen anything like this? Any suggestions would be great.Possibly different SET setting can affect things. Also, you could try SET NO
COUNT ON and see if it
makes any difference.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Wex" <Wex@.discussions.microsoft.com> wrote in message
news:1B68CD56-168D-419F-A01D-8FF310F2EC96@.microsoft.com...
>I have a script to run against a SQL Server 2000 database Windows 2003 OS).
> The script creates temp tables and then uses the manipulated data to updat
e
> the database.
> The probelem is when I run the script in Query Analyzer it takes less then
> 10 minutes to execute. When run the same script using OSQL it takes over
an
> hour.
> Has anyone seen anything like this? Any suggestions would be great.