Output Variable Problem With Dynamic SQL + RAISERROR + TRY/CATCH

Feb 5, 2008

I have a procedure that executes a sql statement passed in as a parameter. The parameter variable is

@pSqlStatement.


CREATE PROCEDURE [dbo].[ProcedureTest]

@pSqlStatement nvarchar(4000)

AS

BEGIN

DECLARE @retVal int;

BEGIN TRY

EXECUTE sp_executesql @pSqlStatement, N'@ret int OUTPUT', @retVal OUTPUT;

PRINT 'try @retVal = ' + ISNULL(CAST(@retVal AS varchar), 'null');

END TRY

BEGIN CATCH

PRINT 'catch @retVal = ' + ISNULL(CAST(@retVal AS varchar), 'null');

END CATCH;

END;

Here is an example of this procedure being called:


EXECUTE [dbo].[ProcedureTest]

@pSQLStatement = N'EXECUTE @ret = [log].[Log.SetSeverityLevel] 'debug'

Note that in the sp_executesql statement, the @ret variable from the dynamic SQL gets assigned to the local variable @retVal.

Here's the problem; when the procedure [log].[Log.SetSeverityLevel] that gets dynamically executed does a RAISERROR, the code in [dbo].[ProcedureTest] falls through to the catch block in [dbo].[ProcedureTest] as it should, but the value of @retVal is null in the catch block, when the return code in [log].[Log.SetSeverityLevel] is set to -1.

If you comment out BEGIN TRY / END TRY / BEGIN CATCH / END CATCH in [dbo].[ProcedureTest], the value of @retVal is correctly seen as -1. There's something about the TRY CATCH structure that's blowing away @retVal when an error is raised and it falls through to the CATCH block.

Anybody ever seen this before? Is there a workaround?

Thanks - Dana

View 7 Replies


ADVERTISEMENT

Using TRY...CATCH With RAISERROR

Jun 1, 2006



Hi, I am trying to write a trigger in SQL 2005 and am running into a lot of issues. Here is my code



BEGIN

BEGIN TRY

DECLARE @count int

--check for timeon which is greater than timeoff

SET @count=0

SELECT @count=count(*)

FROM IVRCONFIG.dbo.C_GROUP_HOURS a WITH (NOLOCK),inserted i

WHERE a.XFER_GROUP = i.XFER_GROUP

AND a.DAY_OF_WEEK = i.DAY_OF_WEEK

AND a.TIMEON = i.TIMEON

AND a.TIMEOFF < a.TIMEON

IF @count<>0 RAISERROR (50001,16,1);

END TRY

BEGIN CATCH

RAISERROR

END CATCH

END

The error I specify is one I added to sys.messages. Can anyone tell me where I am going wrong??

View 1 Replies View Related

Catch Raiserror From ExecuteReader

Feb 27, 2004

Hi. I am executing a stored procedure. The stored procedure raises an error and all I need is to catch this error. Pretty simple, but it only works with an ExecuteNonQuery and not with an Executereader statement. Can anybody explain to me why this happens?

Here's the sp:

CREATE PROCEDURE dbo.rel_test
AS
select 1
raiserror ('My error.', 11, 2)
return
GO

Here's the ASP.Net page:

<% @Page Language="VB" debug="True" %>
<% @Import Namespace="System.Data.SqlClient" %>
<script runat="server">
Public Function RunSP(ByVal strSP As String) As SqlDataReader
Dim o_conn as SqlConnection = New SqlConnection(ConfigurationSettings.AppSettings("connectionstring"))
AddHandler o_conn.InfoMessage, New SqlInfoMessageEventHandler(AddressOf OnInfoMessage)

o_conn.Open

Dim cmd As New SqlCommand(strSP, o_conn)
cmd.CommandType = System.Data.CommandType.StoredProcedure
Dim rdr as SqlDataReader = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection)
rdr.Close()
cmd.Dispose()

Response.Write(o_conn.State)


End Function

Private Sub OnInfoMessage(sender as Object, args as SqlInfoMessageEventArgs)
Dim err As SqlError
For Each err In args.Errors
Response.Write(String.Format("The {0} has received a severity {1}, state {2} error number {3}" & _
"on line {4} of procedure {5} on server {6}:{7}", _
err.Source, err.Class, err.State, err.Number, err.LineNumber, _
err.Procedure, err.Server, err.Message))
Next
End Sub

Sub Page_Load(sender as Object, e as EventArgs)
RunSP("rel_test")
End Sub
</script>

View 2 Replies View Related

TRY..CATCH Block Not Cetching RAISERROR()

Sep 30, 2007

 I guess this is a common problem because I ran into a lot of threads concerning the matter. Unfortunately, none of them helped my situation.I am throw a RAISERROR() in my sql and my vb.net try catch block is not detecting an error. SELECT '3'
RAISERROR('testerror',10,5)  Dim con As New SqlConnection Dim _sqlcommand As New SqlCommand con = New SqlConnection(Spiritopedia.Web.Globals.Settings.General.ConnectionString) _sqlcommand.CommandType = Data.CommandType.StoredProcedure _sqlcommand.CommandText = "TestFunction"
_sqlcommand.Connection = con


'The value to be returned
Dim value As New Object
'Execute the command making sure the connection gets closed in the end

Try

'Open the connection of the command
_sqlcommand.Connection.Open()
'Execute the command and get the number of affected rows 'value = _sqlcommand.ExecuteScalar().ToString()

value = _sqlcommand.ExecuteScalar()


Catch ex As SqlException Throw ex Finally

'Close the connection
_sqlcommand.Connection.Close()
End Try
  

View 6 Replies View Related

.NET 2005 TRY..CATCH With SQL RAISERROR Not Catching

May 28, 2008

Is there a reason why the following code does not raise an error in my .NET 2005 application? Basically I have a try..catch in my stored procedure. Then I have a try...catch in my .NET application that I want to display the error message.
But, when the stored proc raisses the error, the .net code doesn't raise it's error. The .NET code DOES raise an error if I remove the try..catch from the SQL proc and let it error (no error handling), but not if I catch the error and then use RAISERROR to bubble-up the error to .NET app. (I really need to catch the error in my SQL proc and rollback the transaction before I raise the error up to my .NET app...)
SQL
BEGIN TRYBEGIN TRANSACTION trnName
DO MY STUFF....  <---- Error raisedCOMMIT TRANSACTION trnName
END TRY
BEGIN CATCHROLLBACK TRANSACTION trnName
RAISERROR('There was an error',10,1)
 
END CATCH
ASP.NET CODE (No error raised)
Try
daAdapter.SelectCommand.ExecuteNonQuery()Catch ex As SqlException
Err.Raise(50001, "ProcName", "Error:" + ex.Message)
End Try
 

View 4 Replies View Related

Dynamic SQL Variable With Output ??

Jul 23, 2005

I know this has been dealt with a lot, but I would still reallyappreciate help. Thanks.I am trying to transform this tableYY--ID-Code-R1-R2-R3-R4...R402004-1-101--1--2-3-42004-2-101--2--3-4-2....2005-99-103-4-3-2-1Into a table where the new columns are the count for 4-3-2-1 for everydistinct code in the first table based on year. I will get the yearfrom the user-end(Access). I will then create my report based on theinfo in the new table. Here's what I've tried so far (only for 1stcolumn):CREATE PROCEDURE comptabilisationDYN@colonne varchar(3) '*receives R1, then R2, loop is in vba access*ASDECLARE @SQLStatement varchar(8000)DECLARE @TotalNum4 intDECLARE @TotalNum3 intDECLARE @TotalNum2 intDECLARE @TotalNum1 intSELECT SQLStatement = 'SELECT COUNT(*) FROMdbo.Tbl_Réponses_Étudiants WHERE' + @colonne + '=4 AND YY = @year'EXEC sp_executesql @SQLStatement, N'@TotalNum4 int OUTPUT', @TotalNum4OUTPUT INSERT INTO Comptabilisation(Total4) VALUES (@TotalNum4)GO

View 6 Replies View Related

Grab Output Of Dynamic Sql And Use As Variable

May 5, 2008

hello,

I'd like to know how I can grab the output of the following code and use it as variable:

declare @sql nvarchar(25)
set @sql = 'SELECT CURRENT_TIMESTAMP'
EXEC(@sql)

Thank you.

View 2 Replies View Related

Catch Error Message In Variable?

May 24, 2006

Greetings all,

When an error occurs it is written to a log file (Assuming you have loggin on).
Anyone know of a way to catch the error in a variable?

When an error occurs I send an email explaining where there error happened and to view the logfile. I would like to include the last error in the email. Saves having to go view the log...

Thanks

View 14 Replies View Related

T-SQL (SS2K8) :: How To Catch Output Message On Backup Successful Completion / Failure

May 20, 2014

The problem is as follows. SQL Express 2008 R2, backup is made by the means of bat file and sp. Need to have a table that would hold columns like 'date_of_backup', 'duration', 'message' (the one that appears on 'messages' tab in the result area after backup completion/failure). This is an example of real message that I want to catch:

Server: Msg 911, Level 16, State 11, Line 1
Database 'not_existing_db' does not exist. Make sure that the name is entered correctly.
Server: Msg 3013, Level 16, State 1, Line 1
BACKUP DATABASE is terminating abnormally.

View 0 Replies View Related

RAISERROR WITH NOWAIT Vs RAISERROR &#043; RETURN

Dec 19, 2006

I would like to know if there was any semantic differences between the two following statements?

RAISERROR('Invalid argument.',11,1);
RETURN;

or simply

RAISERROR('Invalid argument.',11,1) WITH NOWAIT;

It seems that both statements interrupt the current transaction.

Does anyone has an idea on the subject?

Thanks in advance,
Joannes

View 4 Replies View Related

Try Catch Doesn't Catch Errors Inside A Data Flow Transformation Script Component

Feb 15, 2007

Hi,

I'm having trouble with a Script Component in a data flow task. I have code that does a SqlCommand.ExecuteReader() call that throws an 'Object reference not set to an instance of an object' error. Thing is, the SqlCommand.ExecuteReader() call is already inside a Try..Catch block. Essentially I have two questions regarding this error:

a) Why doesn't my Catch block catch the exception?
b) I've made sure that my SqlCommand object and the SqlConnection property that it uses are properly instantiated, and the query is correct. Any ideas on why it is throwing that exception?

Hope someone could help.

View 3 Replies View Related

SQL 2012 :: Creating Dynamic SSIS File Format - Dynamic CSV File As Output

Mar 2, 2014

I am trying to create an ssis package with dynamic csv file as output. and out format contains query output.

sample file name:

Unique identifier + query output + systemdate();

The expression is looking like this.

@[User::FilePath] + @[User::FileName] + ".CSV"

-- user filepath is a variable from ssis package. File name is the output from SQL query. using script task i have assigned the values to @[User::FileName] .

When I debugged the script task the value getting properly but same variable am using for Flafile destination. but its not working.

View 3 Replies View Related

Dynamic SQL && Output Params

Feb 7, 2005

I have a long running trigger that makes calls to several tables in order to get values for a list of parameters before doing my final INSERT statement into a different table.

One of my parameters is for a local language translation of a particular word which is stored in a table. The problem is - I do not know the name of the table until runtime when I dynamically build the name as follows:


DECLARE @SQL nVarChar(200)
SET @SQL = 'SELECT @Translation = nvcLocalEventDescription FROM Monitoring.dbo.tblSignalTemplate'
+ CAST(@MonitoringCentreID AS nVarChar) + ' WHERE nvcEventDescription = "' + @EventDescription + '"'

EXECUTE Management.dbo.usp_parmsel_LocalEventDescription @SQL, @LocalEventDescription OUTPUT


If there is a MonitoringCentreID of 1234, then there will be a table named tblSignalTemplate1234 - which will contain a nvcLocalEventDescription field containing the value that I am after. Here is the code for the stored procedure...


CREATE PROCEDURE [dbo].[usp_parmsel_LocalEventDescription]
@strSQL nVarchar(150),
@Translation nVarChar(100) OUTPUT
AS
EXECUTE sp_executesql @strSQL
GO


The error I get is "Must declare the variable '@Translation'" - which has thrown me a little as it declared on the 3rd line of the stored proc.

Anyone got any ideas where I am going wrong, or as usual, is there a simpler way ?

Steve.

View 2 Replies View Related

Dynamic Sql And Output Variables

Sep 21, 2004

Hi:

Can anyone tell me if it's possible in SQL Server 2000 to build dynamically a select statement and get some values to variables (simple not tables) from the select ?

Thanks,
Rui Ferreira

View 4 Replies View Related

Dynamic Union All - Output More Columns

Apr 29, 2014

I am having a bit of trouble writing a query that dynamically outputs what I need.

I have a table that looks like this:

COL1 AAA BBB CCC
CAT 1 3 3
CAT 1 2 2
CAT 1 4 4
DOG 2 3 3
DOG 5 5 5
MICE 1 1 1

I need it to dynamically output based off COL1, the output should look like this. When there are more rows for CAT, it should output more columns. Kind of like merging the columns

COL1 AAA BBB CCC AAA BBB CCC AAA BBB CCC
CAT 1 3 3 1 2 2 1 4 4
DOG 2 3 3 5 5 5 NULL NULL NULL
MICE 1 1 1 NULL NULL NULL NULL NULL NULL

View 3 Replies View Related

How To Change Output With Dynamic Pivot

Apr 2, 2015

This is my table.

CREATE TABLE tpivot
([col1] varchar(80), [col2] varchar(80), [col3] varchar(80), [col4] varchar(80), [col5] varchar(80)) ;
INSERT INTO tpivot
([col1], [col2], [col3], [col4], [col5])
VALUES

[code]...

My goal is to turn the table so that the output look like this.

col1 col2 col3 col4 col5
Datum 01.12.2014 02.12.2014 03.12.2014 04.12.2014
EC -204.9 -352.9 -105 -371
Mastercard -88 0 -182 -112.9
Postfinance 0 -79.9 0 -751
VISA -19 -20 -436 -346

I need to have a dynamic pivot since i import the table from a csv that could have different amount of columns each time. I can't even get a static pivot to work.

View 1 Replies View Related

The Dynamic SQL Statements With Output Parameters

Nov 15, 2005

The dynamic SQL statements with output parameters, unfortunately, in the documentation are not described.
À) Simple example of the dynamic SQL statement with output parameters

-- dynamic SQL statements expects parameter of type 'ntext/nchar/nvarchar'.
declare @SQLString nvarchar(4000), @ParmDefinition nvarchar(4000)
-- the third parameter passed in the dynamic statement as by output, returns the length of
-- the hypotenuses of a right triangle, two first parameters are lengths of legs of a triangle
declare @nHypotenuse float
select @SQLString = 'select @nHypotenuse = sqrt(square(@nLeg1_of_a_triangle)+square(@nLeg2_of_a_triangle))',
@ParmDefinition = '@nLeg1_of_a_triangle float, @nLeg2_of_a_triangle float, @nHypotenuse float out'
-- we call the dynamic statement in such a way
exec sp_executesql @SQLString, @ParmDefinition, @nLeg1_of_a_triangle = 3.0, @nLeg2_of_a_triangle = 4.0, @nHypotenuse = @nHypotenuse out
-- or in such a way
exec sp_executesql @SQLString, @ParmDefinition, 3.0, 4.0, @nHypotenuse out
select @nHypotenuse -- Displays 5.0


B) Example of usage of the dynamic statement with output parameter and the function GETALLWORDS.
The following stored procedure get all words from a field of the type text or ntext, the word length should not exceed 4000 characters.

CREATE PROCEDURE SP_GETALLWORDSFROMTEXT
@TableName sysname, @FieldIdName sysname, @FieldIdValue sql_variant, @FieldTextName sysname, @cDelimiters nvarchar(256) = NULL
AS
-- this Stored procedure inserts the words from a text field into the table.
-- WORDNUM int – Sequence number of a word
-- WORD nvarchar(4000) – the word
-- STARTOFWORD int – position in the text field, with which the word starts
-- LENGTHOFWORD smallint – length of the word
-- Parameters
-- @TableName name of the table with the text or ntext field
-- @FieldIdName name of Id field
-- @FieldIdValue value of Id field
-- @FieldTextName name of field text or ntext
-- @cDelimiters Specifies one or more optional characters used to separate words in the text field
begin
set nocount on

declare @k int, @wordcount int, @nBegSubString int, @nEndSubString int, @nEndString int, @divisor tinyint, @flag bit, @RetTable bit,
@cString nvarchar(4000), @TypeField varchar(13), @SQLString nvarchar(4000), @ParmDefinition nvarchar(500), @nBegSubString1 smallint, @nEndSubString1 smallint
select @TableName = object_name(object_id(lower(ltrim(rtrim(@TableName))))), @FieldIdName = lower(ltrim(rtrim(@FieldIdName))), @FieldTextName = lower(ltrim(rtrim(@FieldTextName))),
@cDelimiters = isnull(@cDelimiters, nchar(32)+nchar(9)+nchar(10)+nchar(13)), -- if no break string is specified, the function uses spaces, tabs, carriage return and line feed to delimit words.
@nBegSubString = 1, @nEndSubString = 4000, @flag = 0, @RetTable = 0, @wordcount = 0

-- If the temporary table is not created in the calling procedure, we create the temporary table
if object_id( 'tempdb..#GETALLWORDSFROMTEXT') is null
begin
create table #GETALLWORDSFROMTEXT (WORDNUM int, WORD nvarchar(4000), STARTOFWORD int, LENGTHOFWORD smallint)
select @RetTable = 1
end
-- we use the dynamic SQL statement to receive the exact name of text field
-- as we can write names of fields by a call of the given stored procedure in the arbitrary register
-- in the string of parameters definition @ParmDefinition we use a keyword output
-- and by a call of the dynamic SQL statement exec sp_executesql @SQLString, @ParmDefinition, @FieldTextName = @FieldTextName output
-- Also we use a keyword output for definite before parameter
select @SQLString = 'select @FieldTextName = name from syscolumns where id = OBJECT_ID('''+ @TableName+''') and lower(name) = '''+@FieldTextName+''''
select @ParmDefinition = '@FieldTextName sysname output'
exec sp_executesql @SQLString, @ParmDefinition, @FieldTextName = @FieldTextName output

-- we use the dynamic SQL statement to receive the exact name of Id field
select @SQLString = 'select @FieldIdName = name from syscolumns where id = OBJECT_ID('''+ @TableName+''') and lower(name) = '''+@FieldIdName+''''
select @ParmDefinition = '@FieldIdName sysname output'
exec sp_executesql @SQLString, @ParmDefinition, @FieldIdName = @FieldIdName output

-- we use the dynamic SQL statement to receive the type of field (text or ntext)
select @SQLString = 'select @TypeField = name from systypes where xtype = any ( select xtype from syscolumns where id = OBJECT_ID('''+ @TableName+''') and lower(name) = '''+@FieldTextName+''')'
select @ParmDefinition = '@TypeField varchar(13) output'
exec sp_executesql @SQLString, @ParmDefinition, @TypeField = @TypeField output

select @divisor = case @TypeField when 'ntext' then 2 else 1 end -- 2 for unicode

-- we use the dynamic SQL statement to receive a length of the text field
select @SQLString = 'select @nEndString = 1 + datalength('+ @FieldTextName+')/'+cast( @divisor as nchar(1)) +' from '+@TableName +' where '+ @FieldIdName+' = ' +cast(@FieldIdValue as nchar(50))
select @ParmDefinition = '@nEndString int output'
exec sp_executesql @SQLString, @ParmDefinition, @nEndString = @nEndString output

-- We cut the text field into substrings of length no more than 4000 characters and we work with substrings in cycle
while 1 > 0
begin
-- we use the dynamic SQL statement to receive a substring of a type nvarchar(4000) from text field
select @SQLString = 'select @cString = substring('+ @FieldTextName+','+cast( @nBegSubString as nvarchar(20)) +',' +
cast( @nEndSubString - @nBegSubString + 1 as nvarchar(20))+') from '+@TableName +' where '+ @FieldIdName+' = ' +cast(@FieldIdValue as nchar(50))
select @ParmDefinition = '@cString nvarchar(4000) output'
exec sp_executesql @SQLString, @ParmDefinition, @cString = @cString output

select @nBegSubString1 = 1, @nEndSubString1 = @nEndSubString - @nBegSubString +1

while charindex(substring(@cString, @nBegSubString1, 1) COLLATE Latin1_General_BIN, @cDelimiters COLLATE Latin1_General_BIN) > 0 and @nEndSubString >=@nBegSubString -- skip the character not in word, if any
select @nBegSubString = @nBegSubString + 1 , @nBegSubString1 = @nBegSubString1 + 1

while charindex(substring(@cString, @nEndSubString1, 1) COLLATE Latin1_General_BIN, @cDelimiters COLLATE Latin1_General_BIN) = 0 and @nEndSubString >=@nBegSubString -- skip the character in word, if any
select @nEndSubString = @nEndSubString - 1, @nEndSubString1 = @nEndSubString1 - 1

if @nEndSubString >=@nBegSubString
begin
select top 1 @wordcount = WORDNUM from #GETALLWORDSFROMTEXT order by WORDNUM desc
select @cString = substring(@cString, @nBegSubString1, @nEndSubString1-@nBegSubString1+1)
-- we use a function GETALLWORDS which one works with strings of a type nvarchar(4000)
-- we add outcome result in the temporary table
insert into #GETALLWORDSFROMTEXT (WORDNUM, WORD, STARTOFWORD, LENGTHOFWORD)
select (@wordcount+WORDNUM), WORD, (@nBegSubString+STARTOFWORD-1), LENGTHOFWORD from dbo.GETALLWORDS(@cString, @cDelimiters)

select @nBegSubString = @nEndSubString + 1, @nEndSubString = @nEndSubString + 4000
end
else
select @nEndSubString = @nEndSubString + 4000 -- In a case if the substring consists of one delimiter

if @flag = 1
break
if @nEndString <= @nEndSubString
select @flag = 1, @nEndSubString = @nEndString
end

-- If in a calling procedure the table was not created, we show the result
if @RetTable = 1
select * from #GETALLWORDSFROMTEXT

end
GO



Example of the call Stored procedure SP_GETALLWORDSFROMTEXT


declare @cDelimiters nvarchar(256)
select @cDelimiters = '"-,.:!?«»()'+SPACE(1)+CHAR(9)+CHAR(10)+CHAR(13)+CHAR(12)

if object_id( 'tempdb..#GETALLWORDSFROMTEXT') is not null
drop table #GETALLWORDSFROMTEXT
create table #GETALLWORDSFROMTEXT (WORDNUM int, WORD nvarchar(4000), STARTOFWORD int, LENGTHOFWORD smallint)
exec dbo.SP_GETALLWORDSFROMTEXT 'Your Table name', 'Your Id field name', Value of Id field, ' text or ntext field name', @cDelimiters

if object_id( 'tempdb..#GETALLWORDSFROMTEXT') is not null
select * from #GETALLWORDSFROMTEXT



-- GETALLWORDS() User-Defined Function Inserts the words from a string into the table.
-- GETALLWORDS(@cString[, @cDelimiters])
-- Parameters
-- @cString nvarchar(4000) - Specifies the string whose words will be inserted into the table @GETALLWORDS.
-- @cDelimiters nvarchar(256) - Optional. Specifies one or more optional characters used to separate words in @cString.
-- The default delimiters are space, tab, carriage return, and line feed. Note that GETALLWORDS( ) uses each of the characters in @cDelimiters as individual delimiters, not the entire string as a single delimiter.
-- Return Value table
-- Remarks GETALLWORDS() by default assumes that words are delimited by spaces or tabs. If you specify another character as delimiter, this function ignores spaces and tabs and uses only the specified character.
-- Example
-- declare @cString nvarchar(4000)
-- set @cString = 'The default delimiters are space, tab, carriage return, and line feed. If you specify another character as delimiter, this function ignores spaces and tabs and uses only the specified character.'
-- select * from dbo.GETALLWORDS(@cString, default)
-- select * from dbo.GETALLWORDS(@cString, ' ,.')
-- See Also GETWORDNUM() , GETWORDCOUNT() User-Defined Functions
CREATE function GETALLWORDS (@cString nvarchar(4000), @cDelimiters nvarchar(256))
returns @GETALLWORDS table (WORDNUM smallint, WORD nvarchar(4000), STARTOFWORD smallint, LENGTHOFWORD smallint)
begin
declare @k smallint, @wordcount smallint, @nEndString smallint, @BegOfWord smallint, @flag bit

select @k = 1, @wordcount = 1, @BegOfWord = 1, @flag = 0, @cString = isnull(@cString, ''),
@cDelimiters = isnull(@cDelimiters, nchar(32)+nchar(9)+nchar(10)+nchar(13)), -- if no break string is specified, the function uses spaces, tabs, carriage return and line feed to delimit words.
@nEndString = 1 + datalength(@cString) /(case SQL_VARIANT_PROPERTY(@cString,'BaseType') when 'nvarchar' then 2 else 1 end) -- for unicode

while 1 > 0
begin
if @k - @BegOfWord > 0
begin
insert into @GETALLWORDS (WORDNUM, WORD, STARTOFWORD, LENGTHOFWORD) values( @wordcount, substring(@cString, @BegOfWord, @k-@BegOfWord), @BegOfWord, @k-@BegOfWord ) -- previous word
select @wordcount = @wordcount + 1, @BegOfWord = @k
end
if @flag = 1
break

while charindex(substring(@cString, @k, 1) COLLATE Latin1_General_BIN, @cDelimiters COLLATE Latin1_General_BIN) > 0 and @nEndString > @k -- skip break characters, if any
select @k = @k + 1, @BegOfWord = @BegOfWord + 1
while charindex(substring(@cString, @k, 1) COLLATE Latin1_General_BIN, @cDelimiters COLLATE Latin1_General_BIN) = 0 and @nEndString > @k -- skip the character in the word
select @k = @k + 1
if @k >= @nEndString
select @flag = 1
end
return
end

For more information about string UDFs Transact-SQL please visit the

http://www.universalthread.com/wconnect/wc.dll?LevelExtreme~2,54,33,27115

View 3 Replies View Related

Output Parameter Not Fetched From Dynamic T-SQL Procedure

Sep 9, 2005

I have a STORED PROC for dynamic T-SQL that returns a OUTPUT varaible of typevarchar . This works fine in query analyzer.
But when I try to get values in asp.net page it does not return anything. No execeptions or errors also. Below is the code snippet
HDConn = CommonMethods.BuildConnection();SqlCommand cmd1 = new SqlCommand("GenerateRowids",HDConn);cmd1.CommandType = CommandType.StoredProcedure;// add parameters for Proccmd1.Parameters.Add("@TableName",SqlDbType.VarChar,50).Value= "MetricsMaster";cmd1.Parameters.Add("@ColumnName",SqlDbType.VarChar,50).Value= "MetricId";cmd1.Parameters.Add("@rowidval",SqlDbType.VarChar,30);cmd1.Parameters["@rowidval"].Direction = ParameterDirection.Output;try{cmd1.ExecuteNonQuery();//the below line does not print the valueResponse.Write(cmd1.Parameters["@rowidval"].Value.ToString());}My stored proc looks like :CREATE PROCEDURE dbo.GenerateRowids@TableName varchar(50),@ColumnName varchar(50),@rowidval varchar(30) outputASBegindeclare @sql nvarchar(4000), @Idval varchar(50)
set  @sql = N'select left(MAX(' + @ColumnName +') ,1)+ convert(varchar(5),Cast(SUBSTRING((MAX(' +@ColumnName+ ')),2,(len(MAX(' +@ColumnName+ '))))as int)+1) from  ' + @TableNameexec sp_executesql @query = @sql,@params = N'@rowidval varchar OUTPUT', @rowidval = @rowidval OUTPUT ENDGO

View 11 Replies View Related

Output Parameter Vs (variable) = ?

Jan 18, 2006

Is there any benefit to using Output parameters:eg.[query set-up and execution goes here]

View 2 Replies View Related

Output Variable To Crystal From Sp

May 27, 1999

hey folks...
i am new to store procedures, crystal and sql server... ..one heck of a combination..yikes....neways.... writing a stored procedure in 6.5 to run a crystal report 7.0... want to create an output variable in the procedure that the report will see as a field... can i do this...and if so how....
any and all help muchos gracious.... the higher ups just don't get why i can't do all in 10 days of learning sp's on my own.... egads... management
:-)

take care.....kim

View 2 Replies View Related

Redirect The Output To A Variable

Mar 26, 2008

This is my stored procedure .It is working fine .I want to capture the output in a print statement .Can anyone help me please .

alter proc r (@id INT)

as

BEGIN

DECLARE @input VARCHAR(800)

DECLARE @c_input INT

DECLARE @i_Input INT

DECLARE @input_left VARCHAR(800)

DECLARE @delimiter CHAR(1)

select @delimiter = ','

DECLARE @in VARCHAR(800)

DECLARE @list VARCHAR(800)

declare @list2 VARCHAR(800)



SET @input = 'db2,oracle,sybase'

select @c_input = (select dbo.Fx_CharCount(@delimiter,@input))

set @c_input = @c_input + 1

while @c_input > 0

BEGIN

select @i_input = charindex(@Delimiter,@input)

if @i_input != 0

BEGIN

select @input_left = left(@input, @i_input - 1)

END

else

select @input_left = @input

select @in = '''' + @input_left + ''''

select @list = ISNULL(@list + ',', '') + @in

select @input = right(@input ,(len(@input) - @i_input))

SET @c_input = @c_input -1

if @c_input = 0 or @input = @input_left

break

end

Print @list

EXECUTE ('SELECT Label FROM systemtype WHERE Label Not IN (' + @list + ')')

END




my actual task is like this
My input is a list of values seperated by commas
now my output should be list of values not in the table joined by comma

eg : if my table consists of list of all databases like

db2
oracle,
sybase,
mssql,
mysql,



myinput would be like this db2,sybase,oracle
my output should be mssql,mysql
how to get that
?



Any suggestions

View 2 Replies View Related

Output To Be Redirected To A Variable

Mar 26, 2008

here's my code i want my output to be stored in a variable or out statement .Any suggestions on the below procedure

alter proc r (@id INT)
as
BEGIN

DECLARE @input VARCHAR(800)
DECLARE @c_input INT
DECLARE @i_Input INT
DECLARE @input_left VARCHAR(800)
DECLARE @delimiter CHAR(1)
select @delimiter = ','
DECLARE @inVARCHAR(800)
DECLARE @list VARCHAR(800)
declare @list2 VARCHAR(800)


SET @input = 'AWCA,GCS,IHP,Aetna'
select @c_input = (select dbo.Fx_CharCount(@delimiter,@input))
set @c_input = @c_input + 1
while @c_input > 0
BEGIN
select @i_input = charindex(@Delimiter,@input)
if @i_input != 0
BEGIN
select @input_left = left(@input, @i_input - 1)
END
else
select @input_left = @input

select @in = '''' + @input_left + ''''
select @list = ISNULL(@list + ',', '') + @in

select @input = right(@input ,(len(@input) - @i_input))
SET @c_input = @c_input -1
if @c_input = 0 or @input = @input_left
break
end

PRINT @list

END

View 7 Replies View Related

Store The Output In To A Variable

Mar 26, 2008

This is my stored procedure .It is working fine .I want to capture the output in a print statement .Can anyone help me please .




alter proc r (@id INT)

as

BEGIN

DECLARE @input VARCHAR(800)

DECLARE @c_input INT

DECLARE @i_Input INT

DECLARE @input_left VARCHAR(800)

DECLARE @delimiter CHAR(1)

select @delimiter = ','

DECLARE @in VARCHAR(800)

DECLARE @list VARCHAR(800)

declare @list2 VARCHAR(800)



SET @input = 'AWCA,GCS,IHP,Aetna'

select @c_input = (select dbo.Fx_CharCount(@delimiter,@input))

set @c_input = @c_input + 1

while @c_input > 0

BEGIN

select @i_input = charindex(@Delimiter,@input)

if @i_input != 0

BEGIN

select @input_left = left(@input, @i_input - 1)

END

else

select @input_left = @input

select @in = '''' + @input_left + ''''

select @list = ISNULL(@list + ',', '') + @in

select @input = right(@input ,(len(@input) - @i_input))

SET @c_input = @c_input -1

if @c_input = 0 or @input = @input_left

break

end

Print @list

EXECUTE ('SELECT Label FROM repricingsystemtype WHERE Label Not IN (' + @list + ')')

END



View 5 Replies View Related

Redirect The Output To A Variable

Apr 17, 2008


create procedure usp_test (@AccountID INT)asbegin
DECLARE @getAccountID CURSOR
SET @getAccountID = CURSOR FOR
SELECT Account_ID
FROM Accounts
OPEN @getAccountID
FETCH NEXT
FROM @getAccountID INTO @AccountID
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT @AccountID
FETCH NEXT
FROM @getAccountID INTO @AccountID
END
CLOSE @getAccountID
DEALLOCATE @getAccountIDend i get nearly ten rows in the print statement how can i assign the output to a out variable where i get all ten rows.

View 5 Replies View Related

XML Task And Variable Output?

Feb 20, 2007

Hello,



What I'm trying to do is get an XML query from a database and use the XML to render an excel document. Can this be done using SSIS? Can I actually read a column from a database and store it in a variable and then create an excel spreadsheet with that variable in SSIS? Would this be done in the control flow using the XML task editor?





Thanks,

Phil

View 5 Replies View Related

Output Table As Variable

May 14, 2007

Hi,



I've been looking into using the ability to select the table of an OLEDB destination task based on a package variable but would like to know if this could be utilised in the following example.



I have a CSV file (potentially there are many) with a number of rows. The rows do not necessarily contain the same number of elements. Each row has an EventID and this is used to determine the database table that the row is to be inserted in.



Initially i thought about using a conditional split to send each row down the path relating to its event ID. There would be multiple destinations depending on the table. With the possibility of 60 to 70 different event ID's this is very quickly going to get out of hand in the designer. I'd like to know if it would be possible to set up a case statement (or similar) in a script component and specify the table name as a variable depending on the event ID. I'd then use this table variable to set the destination task's table property.



Does this sound like a possibility or do i have to go down the route of multiple paths?



Many thanks in advance,



Grant

View 3 Replies View Related

OUTPUT @count =no Of Records Returnd By Dynamic Where Clause

Aug 18, 2005

Arvind writes "i want to create a stored procedure returns an OUTPUT variable containing the no. of records given by a query, the query being dynamic.
Preferrably the query should also be passed as a parameter to the stored procedure...If not,it should be constructed in the SP and a Part of the where clause is dependant on the value of another variable passed to the SP.

How should the query be constructed, executed, and then the Count(*) value returned?

"WHERE <condition1> AND <condition 2> ;


"AND <condition 2> " may exist or may not exist in the query; it is dependant."

View 1 Replies View Related

How To Dynamic Set The Variable Value

Apr 1, 2008



In the old DTS package, we can use Active-x script to set the variable value:

DTSGlobalVariables("MessageData").Value = "This is a test"

How do we do the same thing on the SSIS?

I am under the "control Flow" tab.

Thanks.

View 11 Replies View Related

Output Filename Downloaded To A Variable

Sep 7, 2007

Hope I can make this clear...

I have to download a file via FTP from one of our vendors, the filename is MMDDYYYY.zip, this is a weekly file and is posted between Tuesday and Thursday, so basically I never know exactly what the file is going to be called, to fix that, I added a FTP Task that will download a file if the date = today (Today = Thursday, when the job kicks off), if this fails, try a file where the name = today-1 (Wednesday), if this fails, try today-2 (Tuesday), all of that inside of a Sequence Container and with MaximumErrorCount set to 3. This is fine and it works fine, good.

Now my other issue, the .txt file inside the zip file (1080.txt), after being decompressed, needs to be renamed to MMDDYYYY.txt, where MMDDYYY = to the file I downloaded, but I never know what the file is going to named (MMDDYYYY, MMDD-1YYYY, MMDD-2YYYY).

Is it possible to output the filename of the file that I successfully download to a variable, so I can re-use name?

Any other thoughts?

View 1 Replies View Related

Stored Procedure With Output Variable

Jul 20, 2005

Can someone post a working stored procedure with output variable thatworks on northwind db or explain to me what I am missing. I've triedever tying but it always returns @outvariable parameter not supplied.I've read everything but must be missing something. Here is an sampleSP that I can't get to work._____________________________________CREATE PROCEDURE SampleProcedure@out smallint OUTPUTASSelect @out = count(*) from titlesGO_____________________________________This errors and returns-Server: Msg 201, Level 16, State 4, Procedure SampleProcedure, Line 0Procedure 'SampleProcedure' expects parameter '@out', which was notsupplied.What am I missing with this?Frustrated,Jeff

View 2 Replies View Related

How Can I Put The Output Of A Stored Procedure Into A Variable

Nov 8, 2007



hi can anyone please help me
i have a stored procedure ,can i put the value of this into a variable......????
I have one more query ---how can i pass the multiple values returned by this stored procedure into a single variable ...
example if my stored procedure is

[dbo].[GetPortfolioName](@NT_Account varchar(100) )
and ans of this are
NL
UK
IN
GN
JK
then how can i put this into a variable like

Declare @PortfolioName as varchar(250)
set @PortfolioName =(exec ].[GetPortfolioName](@NT_Account) )
.......
and my ans is
@PortfolioName = 'NL','UK','IN','GN','JK'

View 22 Replies View Related

Mapping Output Parameter To A Variable!

Apr 25, 2007

Hi there,

I am working on SSIS package that gets data from SQL 2005 Database and writes that to a flat file. But I need to write the count of records as part of the header.

Here is what i am trying:

The OLE DB Source is calling a stored procedure and returning two things i.e. a resultset and an output parameter. The data access mode is SQL Command.



Code SnippetEXEC [Get_logins] ?, ?, ? OUTPUT


In the Set Query Parameters dialogbox, all the three patameters are mapped to three different user variables.

What is happening is that the user variable that is mapped to output parameter is never updated. The header property expression is written as follows




Code SnippetRIGHT("0000000000" + (DT_STR, 10, 1252)@LoginCount, 10)



I tried to watch the variable in watch window but to no avail. Any guidance if it is bug or I am missing some thing? Any thoughts, how can I accomplish this? I have also tried adding Row Count Transformation but its variable has the same behaviour. If I set the value of @LoginCount variable to some value, this initially set value is successfully written to the file header.

Thanks

Paraclete

View 4 Replies View Related

ExecuteSQL Using SQLSource Variable And Output

Nov 16, 2007



Really stuck trying different ways to get a string variable (expression based) to parse and run correctly in an ExecuteSQL task. Would someone be able to advise why one of the following methods works and the other does not?
I'd really prefer to have the second currently not working method be used if possible.

WORKS:
"[audit].[up_LogEtlPackageStart]
@ETLAuditParentKey = ?,
@Description = ?,
@PackageName = ?,
@PackageGuid = ?,
@PackageVersionMajor = ?,
@PackageVersionMinor = ?,
@PackageVersionBuild = ?,
@MachineName = ?,
@ExecutionGuid = ?,
@LogicalDate = ?,
@StartTime = ?,
@Operator = ?,
@ETLAuditKey = ? OUTPUT"

FAILS:
When the variable expression is set as follows I :



Code Block

"[audit].[up_LogEtlPackageStart]
@ETLAuditParentKey = " + (DT_WSTR, 100)@[User::ETLAuditParentKey] + ",
@Description = " + (LEN( @[User::PackageDescription]) == 0 ? "' '" : @[User::PackageDescription]) + ",
@PackageName = " + @[System::PackageName] + ",
@PackageGuid = " + @[System::PackageID] + ",
@PackageVersionMajor = " + (DT_WSTR, 100)@[System::VersionMajor] + ",
@PackageVersionMinor = " + (DT_WSTR, 100)@[System::VersionMinor] + ",
@PackageVersionBuild = " + (DT_WSTR, 100)@[System::VersionBuild] + ",
@MachineName = " + @[System::MachineName] + ",
@ExecutionGuid = " + @[System::ExecutionInstanceGUID] + ",
@LogicalDate = " + (DT_WSTR, 100)@[User::LogicalDate] + ",
@StartTime = " + (DT_WSTR, 100)@[System::StartTime] + ",
@Operator = " + @[System::UserName] + ",
@ETLAuditKey = " + (DT_WSTR, 100)@[User::ETLAuditKey] + " OUTPUT"




This method generates a "Syntax error, permission violation, or other nonspecific error. Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly"

Any ways to get the second failing expression to work?
Is this a problem due to the OUTPUT parameter?
THANKS!

View 7 Replies View Related







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