Showing posts with label varchar. Show all posts
Showing posts with label varchar. Show all posts

Friday, March 23, 2012

Right way to do a insert

Just to make sure - is this the right way to do a simple insert?
Create PROCEDURE dbo.spInsert(
@.name varchar(50))
AS
begin tran
set nocount on
insert into tbl (name) values(@.name)
set nocount off
declare @.id int
set @.id = @.@.IDENTITY
commit tran
return @.idMichael,
There's no need for an explicit transaction if there's no more than a single
INSERT or UPDATE in a batch. But it wont do any harm either :)
More important thing: don't use @.@.IDENTITY function, but use
SCOPE_IDENTITY() instead, it's much more reliable (many will argue that you
shouldn't use the identity property at all..). Also, use an OUTPUT param to
return the identity value to calling application, and save RETURN for
success/fail code.
And, you should really check the @.@.ERROR value after each statement (or,
with 2005, use the TRY..CATCH). Check these excellent articles for a
detailed explanation of error handling inside T-SQL:
http://www.sommarskog.se/error-handling-I.html
http://www.sommarskog.se/error-handling-II.html
Dean
"Michael Fllgreen" <mfa@.ulle.se> wrote in message
news:OpostIYZGHA.1192@.TK2MSFTNGP04.phx.gbl...
> Just to make sure - is this the right way to do a simple insert?
> Create PROCEDURE dbo.spInsert(
> @.name varchar(50))
> AS
> begin tran
> set nocount on
> insert into tbl (name) values(@.name)
> set nocount off
> declare @.id int
> set @.id = @.@.IDENTITY
> commit tran
> return @.id
>|||A few comments here:
First of all, I'd tend to SET NOCOUNT ON at the start of the procedure,
before beginning a transaction -- but that might be more of a style thing.
In addition, there's really no reason to ever SET NOCOUNT OFF in a stored
procedure.
Second, you probably don't need an explicit transaction in this case. The
INSERT has its own implicit transaction, and you really only need an
explicit one if you're doing multiple DML operations at the same time (or,
if you need to serialize reads or do other things that are not too common in
most apps).
Third, you should avoid @.@.IDENTITY, assuming you're using SQL Server 2000 or
later. @.@.IDENTITY can return seemingly-erroneous results if another insert
happens due to a trigger firing. This can cause issues that can be very
tough to debug. Instead, use the SCOPE_IDENTITY function, which doesn't
have that problem.
Finally, I personally avoid using RETURN in stored procedures; instead, I
much prefer OUTPUT parameters. The return value is set by SQL Server when
exceptions occur, and I feel that overriding it is a form of in-band
signalling.
So given all of this, I would write your procedure as:
CREATE PROCEDURE dbo.spInsert
@.name VARCHAR(50),
@.ID INT OUTPUT
AS
BEGIN
SET NOCOUNT ON
INSERT tbl (name)
VALUES (@.name)
SET @.ID = SCOPE_IDENTITY()
END
GO
Adam Machanic
Pro SQL Server 2005, available now
http://www.apress.com/book/bookDisplay.html?bID=457
--
"Michael Fllgreen" <mfa@.ulle.se> wrote in message
news:OpostIYZGHA.1192@.TK2MSFTNGP04.phx.gbl...
> Just to make sure - is this the right way to do a simple insert?
> Create PROCEDURE dbo.spInsert(
> @.name varchar(50))
> AS
> begin tran
> set nocount on
> insert into tbl (name) values(@.name)
> set nocount off
> declare @.id int
> set @.id = @.@.IDENTITY
> commit tran
> return @.id
>|||"Michael Fllgreen" <mfa@.ulle.se> wrote in message
news:OpostIYZGHA.1192@.TK2MSFTNGP04.phx.gbl...
> Just to make sure - is this the right way to do a simple insert?
> Create PROCEDURE dbo.spInsert(
> @.name varchar(50))
> AS
> begin tran
> set nocount on
> insert into tbl (name) values(@.name)
> set nocount off
> declare @.id int
> set @.id = @.@.IDENTITY
> commit tran
> return @.id
>
Looks OK but there are a few things you could change. The transaction is
unnecessary because there is only one DML statement involved, i.e. the
INSERT is the only thing that modifies data. NOCOUNT is scoped to the proc
so your NOCOUNT OFF does nothing useful. In SQL Server 2000 and 2005
SCOPE_IDENTITY() is usually preferred to @.@.IDENTITY because it won't be
affected by any triggers on the table. Finally, the RETURN status is
normally used to return success or error. Use OUTPUT parameters for other
values.
In a production application you should also add error handling. I've not
done that here because you didn't say what version you are using and that
matters a lot.
CREATE PROCEDURE dbo.spInsert(
@.name VARCHAR(50),
@.id INT OUTPUT)
AS
SET NOCOUNT ON ;
DECLARE @.r INT ;
INSERT INTO dbo.tbl (name) VALUES(@.name);
SET @.ID = SCOPE_IDENTITY();
SET @.r = @.@.ERROR ;
RETURN @.r ;
GO
DECLARE @.i INT, @.r INT ;
EXEC @.r = dbo.spInsert 'foo', @.i OUTPUT ;
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||"David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> wrote in message
news:eblLZSYZGHA.3652@.TK2MSFTNGP03.phx.gbl...
> INSERT INTO dbo.tbl (name) VALUES(@.name);
> SET @.ID = SCOPE_IDENTITY();
> SET @.r = @.@.ERROR ;
Shouldn't this be:
INSERT INTO dbo.tbl (name) VALUES(@.name);
SELECT
@.ID = SCOPE_IDENTITY(),
@.r = @.@.ERROR ;
? Otherwise, won't @.@.ERROR reset thanks to the SCOPE_IDENTITY() line?
By the way, I personally would not put error handling in here, even in a
production app, since there's only one DML statement. Might as well let the
app handle the problem, IMO.
Adam Machanic
Pro SQL Server 2005, available now
http://www.apress.com/book/bookDisplay.html?bID=457
--|||Thanks alot all. BTW - im on a SQL Server 2005
Don't get the errorhandling thoug - i mean - I'm not going to do anything
about the error anyway. If the insert fails it fails with a standard
err.message. Why would i whanna catch an error in a simpel insert ?
Thanks
"David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> skrev i en
meddelelse news:eblLZSYZGHA.3652@.TK2MSFTNGP03.phx.gbl...
> "Michael Fllgreen" <mfa@.ulle.se> wrote in message
> news:OpostIYZGHA.1192@.TK2MSFTNGP04.phx.gbl...
> Looks OK but there are a few things you could change. The transaction is
> unnecessary because there is only one DML statement involved, i.e. the
> INSERT is the only thing that modifies data. NOCOUNT is scoped to the proc
> so your NOCOUNT OFF does nothing useful. In SQL Server 2000 and 2005
> SCOPE_IDENTITY() is usually preferred to @.@.IDENTITY because it won't be
> affected by any triggers on the table. Finally, the RETURN status is
> normally used to return success or error. Use OUTPUT parameters for other
> values.
> In a production application you should also add error handling. I've not
> done that here because you didn't say what version you are using and that
> matters a lot.
> CREATE PROCEDURE dbo.spInsert(
> @.name VARCHAR(50),
> @.id INT OUTPUT)
> AS
> SET NOCOUNT ON ;
> DECLARE @.r INT ;
> INSERT INTO dbo.tbl (name) VALUES(@.name);
> SET @.ID = SCOPE_IDENTITY();
> SET @.r = @.@.ERROR ;
> RETURN @.r ;
> GO
> DECLARE @.i INT, @.r INT ;
> EXEC @.r = dbo.spInsert 'foo', @.i OUTPUT ;
> --
> David Portas, SQL Server MVP
> Whenever possible please post enough code to reproduce your problem.
> Including CREATE TABLE and INSERT statements usually helps.
> State what version of SQL Server you are using and specify the content
> of any error messages.
> SQL Server Books Online:
> http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
> --
>|||"Adam Machanic" <amachanic@.hotmail._removetoemail_.com> wrote in message
news:e79chVYZGHA.4836@.TK2MSFTNGP05.phx.gbl...
> "David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> wrote in message
> news:eblLZSYZGHA.3652@.TK2MSFTNGP03.phx.gbl...
> Shouldn't this be:
> INSERT INTO dbo.tbl (name) VALUES(@.name);
> SELECT
> @.ID = SCOPE_IDENTITY(),
> @.r = @.@.ERROR ;
>
> ? Otherwise, won't @.@.ERROR reset thanks to the SCOPE_IDENTITY() line?
> By the way, I personally would not put error handling in here, even in
> a production app, since there's only one DML statement. Might as well let
> the app handle the problem, IMO.
>
I would only put error handling here in SQL 2000, and only for the case
where this procedure is called from another procedure. In SQL 2005 a
calling procedure can CATCH the error, and doesn't need a return value to
know if the execution failed.
Also I would omit the dbo. in the table reference and the procedure name
because there's no performance reason to have it there, and as a general
practice of naming, objects in the same namespace (schema) should refer to
each other with relative names.
CREATE PROCEDURE MyTable_Insert
@.name VARCHAR(50),
@.ID INT OUTPUT
AS
BEGIN
SET NOCOUNT ON
INSERT MyTable (name)
VALUES (@.name)
IF @.@.ERROR <> 0 RETURN @.@.ERROR
SET @.ID = SCOPE_IDENTITY()
END
David|||Adam Machanic wrote:
> "David Portas" <REMOVE_BEFORE_REPLYING_dportas@.acm.org> wrote in message
> news:eblLZSYZGHA.3652@.TK2MSFTNGP03.phx.gbl...
> Shouldn't this be:
> INSERT INTO dbo.tbl (name) VALUES(@.name);
> SELECT
> @.ID = SCOPE_IDENTITY(),
> @.r = @.@.ERROR ;
>
> ? Otherwise, won't @.@.ERROR reset thanks to the SCOPE_IDENTITY() line?
True. Good catch.

> By the way, I personally would not put error handling in here, even in
a
> production app, since there's only one DML statement. Might as well let t
he
> app handle the problem, IMO.
I would handle the error with TRY CATCH in 2005. In 2000 I might leave
out error handling if the application dealt with it but most of the
time I log errors to a table or the log.
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||Michael F=E4llgreen wrote:
> Thanks alot all. BTW - im on a SQL Server 2005
> Don't get the errorhandling thoug - i mean - I'm not going to do anything
> about the error anyway. If the insert fails it fails with a standard
> err.message. Why would i whanna catch an error in a simpel insert ?
> Thanks
If INSERTs fail intermittently for some reason can you be sure the
users will call support every time? If you catch and log the error
you'll know about it sooner and you can capture enough information to
make it easier to debug.
David Portas, SQL Server MVP
Whenever possible please post enough code to reproduce your problem.
Including CREATE TABLE and INSERT statements usually helps.
State what version of SQL Server you are using and specify the content
of any error messages.
SQL Server Books Online:
http://msdn2.microsoft.com/library/ms130214(en-US,SQL.90).aspx
--|||"Adam Machanic" <amachanic@.hotmail._removetoemail_.com> wrote in message
news:%23yvmfQYZGHA.1200@.TK2MSFTNGP03.phx.gbl...
>A few comments here:
> First of all, I'd tend to SET NOCOUNT ON at the start of the procedure,
> before beginning a transaction -- but that might be more of a style thing.
> In addition, there's really no reason to ever SET NOCOUNT OFF in a stored
> procedure.
>
That depends on what you're doing. ADO.NET makes use of the rows affected
to determine whether or not to throw a System.Data.DBConcurrencyException.
For procedures called from ADO.NET, execute SET NOCOUNT ON at the start of
the procedure, and then immediately before executing the statement that
writes to the database, SET NOCOUNT OFF.

> Second, you probably don't need an explicit transaction in this case. The
> INSERT has its own implicit transaction, and you really only need an
> explicit one if you're doing multiple DML operations at the same time (or,
> if you need to serialize reads or do other things that are not too common
> in most apps).
> Third, you should avoid @.@.IDENTITY, assuming you're using SQL Server 2000
> or later. @.@.IDENTITY can return seemingly-erroneous results if another
> insert happens due to a trigger firing. This can cause issues that can be
> very tough to debug. Instead, use the SCOPE_IDENTITY function, which
> doesn't have that problem.
> Finally, I personally avoid using RETURN in stored procedures; instead, I
> much prefer OUTPUT parameters. The return value is set by SQL Server when
> exceptions occur, and I feel that overriding it is a form of in-band
> signalling.
>
I don't think that a stored procedure's return value is set by the database
engine when exceptions or errors occur. Another mechanism is used to inform
the client because more than one error can occur within a procedure since
some don't kill the entire batch--instead, just the offending statement is
terminated.
I prefer to use return values to pass back status, and output parameters to
pass back other information, such as identity and rowversion.

> So given all of this, I would write your procedure as:
> CREATE PROCEDURE dbo.spInsert
> @.name VARCHAR(50),
> @.ID INT OUTPUT
> AS
> BEGIN
> SET NOCOUNT ON
> INSERT tbl (name)
> VALUES (@.name)
> SET @.ID = SCOPE_IDENTITY()
> END
> GO
>
> --
> Adam Machanic
> Pro SQL Server 2005, available now
> http://www.apress.com/book/bookDisplay.html?bID=457
> --
>
> "Michael Fllgreen" <mfa@.ulle.se> wrote in message
> news:OpostIYZGHA.1192@.TK2MSFTNGP04.phx.gbl...
>

right blank space in sql

I need ti getthe length of a string like this (varchar or char doesn't matte
r)
'AB12345678A '. The length is 14, but the function len('AB12345678A ')
return 11. Len doesn't count the blank spaces. How con i get yhe length of m
y
strings including blank spaces?Hi
It depends on the ANSI_PADDING setting for you DB, but LEN will always
return the number of characters, right trimmed.
If ANSI_PADDING is ON when the data it put into the DB, you could use this
work around:
SELECT LEN('AB12345678A ' + '.') -1
This will cause a "." (or any other character) to be appended after the
blanks, so LEN will not trim it, then subtract one from the total count to
compensate for the "."
Regards
--
Mike Epprecht, Microsoft SQL Server MVP
Zurich, Switzerland
IM: mike@.epprecht.net
MVP Program: http://www.microsoft.com/mvp
Blog: http://www.msmvps.com/epprecht/
"checcouno" <checcouno@.discussions.microsoft.com> wrote in message
news:F8C0249C-6E56-465A-995E-A0AF0701F8F8@.microsoft.com...
> I need ti getthe length of a string like this (varchar or char doesn't
matter)
> 'AB12345678A '. The length is 14, but the function len('AB12345678A ')
> return 11. Len doesn't count the blank spaces. How con i get yhe length of
my
> strings including blank spaces?|||Hi,
I have used Datalength fucntion it gives me value 14.
Read BOL for Datalength and Len function
Thanks
AM
"Mike Epprecht (SQL MVP)" <mike@.epprecht.net> wrote in message
news:%233v1nu5KFHA.2796@.tk2msftngp13.phx.gbl...
> Hi
> It depends on the ANSI_PADDING setting for you DB, but LEN will always
> return the number of characters, right trimmed.
> If ANSI_PADDING is ON when the data it put into the DB, you could use this
> work around:
> SELECT LEN('AB12345678A ' + '.') -1
> This will cause a "." (or any other character) to be appended after the
> blanks, so LEN will not trim it, then subtract one from the total count to
> compensate for the "."
> Regards
> --
> Mike Epprecht, Microsoft SQL Server MVP
> Zurich, Switzerland
> IM: mike@.epprecht.net
> MVP Program: http://www.microsoft.com/mvp
> Blog: http://www.msmvps.com/epprecht/
> "checcouno" <checcouno@.discussions.microsoft.com> wrote in message
> news:F8C0249C-6E56-465A-995E-A0AF0701F8F8@.microsoft.com...
> matter)
')
of
> my
>|||"checcouno" <checcouno@.discussions.microsoft.com> wrote in message
news:F8C0249C-6E56-465A-995E-A0AF0701F8F8@.microsoft.com...
>I need ti getthe length of a string like this (varchar or char doesn't
>matter)
> 'AB12345678A '. The length is 14, but the function len('AB12345678A ')
> return 11. Len doesn't count the blank spaces. How con i get yhe length of
> my
> strings including blank spaces?
Try DATALENGTH instead.
SELECT LEN('AB12345678A ') returns 11
SELECT DATALENGTH('AB12345678A ') returns 14
Dan

Wednesday, March 7, 2012

Returning values from Stored Procedure

Hi Using Following Stored Procedure,

Which always returns Null,

What s the error,

CREATE PROCEDURE prLoginAuth

(

@.pStrUserName varchar(50),
@.pStrPassword varchar(50),
@.pOutput Varchar(20) Output
)

AS

Declare @.V_Facilities Varchar(50)

SELECT Facilities=@.V_Facilities From UserLoginFacilities where LoginID=(Select LoginID From UserLogin where LoginName=@.pStrUserName and Password=@.pStrPassword)

If(@.V_Facilities=null)

Set @.pOutput = @.V_Facilities

Return @.pOutput;

Else

Set @.pOutput = @.V_Facilities

Return @.pOutput;

GO

Anyone correct this query , I want return the output from this procedure

Thanx in advance

Selva.R

I believe you are mixing two techniques for returning data from a stored procedure.

1. If you declare the parameter 'pOutput' as an output type parameter, you should NOT use it as the return value from the stored procedure. Simply assigning a value to it does the trick. (e.g. Select @.pOutput = @.V_Facilities). You pickup the result from your parameters collection.

2. If you decide to return the result as the returncode from the stored procedure, there is no need to define a parameter from the type OUTPUT. You just return the value (e.g. RETURN @.V_Facilities) and pick it up as the return value from your ExecuteScalar method

Hope this helps.

|||

In addition to what has already been mentioned, you can only ever return an integer using RETURN in a stored procedure. So any value that you try to return would have to be convertable to an integer ('0001' ok, 'hey joe' not ok :)

Second, you are never setting the value of @.V_Facilites, and I am guessing (since you didn't provide data or output :) that you are getting back a result set with a null value, as well as the return value = null

To set the value of a parameter to a column value, the syntax is:

SELECT @.variableName = column
FROM ....

Turned the other way around, it is an older syntax for renaming the output name of a column, so it wouldn't matter what was in the FROM clause, it would still return the value of the variable (in this case null since you haven't initialized it). For example:

DECLARE @.testValue int
SET @.testValue = 1

SELECT bob = @.testValue
--FROM anything

Returns

bob
--
1

Returning Value from stored procedure

I wrote a Stored Procedure as below:
CREATE PROCEDURE sp_AssignActPass (@.CustID varchar(4), @.UserID
varchar(7),@.ActPass varchar(45),@.LastUpdate datetime)
AS
UPDATE MemberSET ActPass = @.ActPass, LastUpdate = CURRENT_TIMESTAMP
WHERE CustID = @.CustID AND UserID = @.UserID AND LastUpdate = @.LastUpdate
IF @.@.ROWCOUNT = 0
BEGIN
IF EXISTS(SELECT UserID FROM Member WHERE CustID = @.CustID AND UserID =
@.UserID)
RETURN '2' -- Concurrency Conflict
ELSE
RETURN '1' -- Record has been deleted
END
ELSE
RETURN '0' -- Record has been updated
GO
The content is not important. The issue here is when I execute this Stored
Procedure, I don't get 0, 1 or 2 as a result. It only tells me how many rows
are affected. Why? I thought I should see 0, 1, or 2?
Thank you in advancere-write the Procedure as
CREATE PROCEDURE sp_AssignActPass (@.CustID varchar(4), @.UserID
varchar(7),@.ActPass varchar(45),@.LastUpdate datetime), @.result int OUTPUT
AS
UPDATE MemberSET ActPass = @.ActPass, LastUpdate = CURRENT_TIMESTAMP
WHERE CustID = @.CustID AND UserID = @.UserID AND LastUpdate = @.LastUpdate
IF @.@.ROWCOUNT = 0
BEGIN
IF EXISTS(SELECT UserID FROM Member WHERE CustID = @.CustID AND UserID =
@.UserID)
SET @.result = 2
ELSE
SET @.result = 1
END
ELSE
SET @.result = 0
RETURN @.result
GO
best Regards,
Chandra
---
"wrytat" wrote:

> I wrote a Stored Procedure as below:
> CREATE PROCEDURE sp_AssignActPass (@.CustID varchar(4), @.UserID
> varchar(7),@.ActPass varchar(45),@.LastUpdate datetime)
> AS
> UPDATE MemberSET ActPass = @.ActPass, LastUpdate = CURRENT_TIMESTAMP
> WHERE CustID = @.CustID AND UserID = @.UserID AND LastUpdate = @.LastUpdate
> IF @.@.ROWCOUNT = 0
> BEGIN
> IF EXISTS(SELECT UserID FROM Member WHERE CustID = @.CustID AND UserID =
> @.UserID)
> RETURN '2' -- Concurrency Conflict
> ELSE
> RETURN '1' -- Record has been deleted
> END
> ELSE
> RETURN '0' -- Record has been updated
> GO
> The content is not important. The issue here is when I execute this Stored
> Procedure, I don't get 0, 1 or 2 as a result. It only tells me how many ro
ws
> are affected. Why? I thought I should see 0, 1, or 2?
> Thank you in advance|||The return value isnt present to the result, it is a result which can be
get via special properties in the providers, or within a TSQL statement:
DECLARE Returncode int
EXEC @.RC = Someproc
YOu can refer to the Return syntax on BOL.
Sample:
<BOLSample>
CREATE PROCEDURE checkstate @.param varchar(11)
AS
IF (SELECT state FROM authors WHERE au_id = @.param) = 'CA'
RETURN 1
ELSE
RETURN 2
DECLARE @.return_status int
EXEC @.return_status = checkstate '172-32-1176'
SELECT 'Return Status' = @.return_status
GO
</BOLSample>
HTH, Jens Suessmeyer.
http://www.sqlserver2005.de
--
"wrytat" <wrytat@.discussions.microsoft.com> schrieb im Newsbeitrag
news:466A14D8-2256-47D2-8ECC-C0576672078F@.microsoft.com...
>I wrote a Stored Procedure as below:
> CREATE PROCEDURE sp_AssignActPass (@.CustID varchar(4), @.UserID
> varchar(7),@.ActPass varchar(45),@.LastUpdate datetime)
> AS
> UPDATE MemberSET ActPass = @.ActPass, LastUpdate = CURRENT_TIMESTAMP
> WHERE CustID = @.CustID AND UserID = @.UserID AND LastUpdate = @.LastUpdate
> IF @.@.ROWCOUNT = 0
> BEGIN
> IF EXISTS(SELECT UserID FROM Member WHERE CustID = @.CustID AND UserID =
> @.UserID)
> RETURN '2' -- Concurrency Conflict
> ELSE
> RETURN '1' -- Record has been deleted
> END
> ELSE
> RETURN '0' -- Record has been updated
> GO
> The content is not important. The issue here is when I execute this Stored
> Procedure, I don't get 0, 1 or 2 as a result. It only tells me how many
> rows
> are affected. Why? I thought I should see 0, 1, or 2?
> Thank you in advance|||I get an error message.
Erro1 170: Line 3: Incorrect syntax near ','.
Must declare the variable '@.result'.
Must declare the variable '@.result'.
Must declare the variable '@.result'.
Must declare the variable '@.result'.
"Chandra" wrote:
> re-write the Procedure as
> CREATE PROCEDURE sp_AssignActPass (@.CustID varchar(4), @.UserID
> varchar(7),@.ActPass varchar(45),@.LastUpdate datetime), @.result int OUTPUT
> AS
> UPDATE MemberSET ActPass = @.ActPass, LastUpdate = CURRENT_TIMESTAMP
> WHERE CustID = @.CustID AND UserID = @.UserID AND LastUpdate = @.LastUpdate
> IF @.@.ROWCOUNT = 0
> BEGIN
> IF EXISTS(SELECT UserID FROM Member WHERE CustID = @.CustID AND UserID =
> @.UserID)
> SET @.result = 2
> ELSE
> SET @.result = 1
> END
> ELSE
> SET @.result = 0
> RETURN @.result
> GO
>
> --
> best Regards,
> Chandra
> ---
>
> "wrytat" wrote:
>|||Then is it possible to get this returned value in the codings of ASP.nEt
"Jens Sü?meyer" wrote:

> The return value isn′t present to the result, it is a result which can be
> get via special properties in the providers, or within a TSQL statement:
> DECLARE Returncode int
> EXEC @.RC = Someproc
> YOu can refer to the Return syntax on BOL.
> Sample:
> <BOLSample>
> CREATE PROCEDURE checkstate @.param varchar(11)
> AS
> IF (SELECT state FROM authors WHERE au_id = @.param) = 'CA'
> RETURN 1
> ELSE
> RETURN 2
> DECLARE @.return_status int
> EXEC @.return_status = checkstate '172-32-1176'
> SELECT 'Return Status' = @.return_status
> GO
> </BOLSample>
> HTH, Jens Suessmeyer.
> --
> http://www.sqlserver2005.de
> --
>
> "wrytat" <wrytat@.discussions.microsoft.com> schrieb im Newsbeitrag
> news:466A14D8-2256-47D2-8ECC-C0576672078F@.microsoft.com...
>
>|||Just declare it here:
WHERE CustID = @.CustID AND UserID = @.UserID AND LastUpdate = @.LastUpdate
DECLARE @.Result INT --<-- HERE
IF @.@.ROWCOUNT = 0
HTH, Jens Suessmeyer.
http://www.sqlserver2005.de
--
"wrytat" <wrytat@.discussions.microsoft.com> schrieb im Newsbeitrag
news:B7C2766B-C908-4350-ADEC-BBCA688C88B1@.microsoft.com...
>I get an error message.
> Erro1 170: Line 3: Incorrect syntax near ','.
> Must declare the variable '@.result'.
> Must declare the variable '@.result'.
> Must declare the variable '@.result'.
> Must declare the variable '@.result'.
>
> "Chandra" wrote:
>|||Just not to let you run in further problems, it depends on how you get dour
data:
http://support.microsoft.com/kb/308051/EN-US/
HTH, Jens Suessmeyer.
http://www.sqlserver2005.de
--
"wrytat" <wrytat@.discussions.microsoft.com> schrieb im Newsbeitrag
news:FDE41EAF-8646-404A-A22E-0602471360FF@.microsoft.com...
> Then is it possible to get this returned value in the codings of ASP.nEt
> "Jens Smeyer" wrote:
>|||sorry! my mistake
CREATE PROCEDURE sp_AssignActPass (@.CustID varchar(4), @.UserID
varchar(7),@.ActPass varchar(45),@.LastUpdate datetime, @.result int OUTPUT)
AS
UPDATE MemberSET ActPass = @.ActPass, LastUpdate = CURRENT_TIMESTAMP
WHERE CustID = @.CustID AND UserID = @.UserID AND LastUpdate = @.LastUpdate
IF @.@.ROWCOUNT = 0
BEGIN
IF EXISTS(SELECT UserID FROM Member WHERE CustID = @.CustID AND UserID =
@.UserID)
SET @.result = 2
ELSE
SET @.result = 1
END
ELSE
SET @.result = 0
RETURN @.result
GO
hope this will work now
best Regards,
Chandra
---
"wrytat" wrote:
> I get an error message.
> Erro1 170: Line 3: Incorrect syntax near ','.
> Must declare the variable '@.result'.
> Must declare the variable '@.result'.
> Must declare the variable '@.result'.
> Must declare the variable '@.result'.
>
> "Chandra" wrote:
>

Tuesday, February 21, 2012

Returning long string in varchar using Coalesce()

Hi,
I want to return a string of words separated by comma using coalesce() so
that the client application can look for a specific word in this long
string.Following is the script:-
CREATE TABLE WordList
(
WordId int IDENTITY,
WordDesc varchar(100)
)
INSERT INTO WordList VALUES ('Lion')
INSERT INTO WordList VALUES ('Goat')
INSERT INTO WordList VALUES ('Snake')
DECLARE @.WordList varchar(8000)
SELECT @.WordList = COALESCE(@.WordList + ', ', '') + WordDesc
FROM WordList
SELECT @.WordList AS WordList
Above approach works fine.However,as the maximum size for varchar is
8000,any longer string will be truncated.I can not use "text" datatype for
this as it is not allowed.
Any workaround?Any pointers?you cannot declare a variable of text datatype. Of course in 2005 I think yo
u
can do that because its been replaced as varchar(max). Hope this helps.
"Ashish" wrote:

> Hi,
> I want to return a string of words separated by comma using coalesce() so
> that the client application can look for a specific word in this long
> string.Following is the script:-
>
> CREATE TABLE WordList
> (
> WordId int IDENTITY,
> WordDesc varchar(100)
> )
> INSERT INTO WordList VALUES ('Lion')
> INSERT INTO WordList VALUES ('Goat')
> INSERT INTO WordList VALUES ('Snake')
>
> DECLARE @.WordList varchar(8000)
> SELECT @.WordList = COALESCE(@.WordList + ', ', '') + WordDesc
> FROM WordList
> SELECT @.WordList AS WordList
>
> Above approach works fine.However,as the maximum size for varchar is
> 8000,any longer string will be truncated.I can not use "text" datatype for
> this as it is not allowed.
> Any workaround?Any pointers?
>|||Correct.Thank you.I am aware of the same.But i am using Sql 2000 and looking
for a workaround for this.
"Omnibuzz" wrote:
> you cannot declare a variable of text datatype. Of course in 2005 I think
you
> can do that because its been replaced as varchar(max). Hope this helps.
> --
>
>
> "Ashish" wrote:
>|||Perform concatenation at the client / presentation layer?

> Above approach works fine.However,as the maximum size for varchar is
> 8000,any longer string will be truncated.I can not use "text" datatype for
> this as it is not allowed.
> Any workaround?Any pointers?|||I want to avoid returning resultset to the presentatio layer.If i would want
i would make use of the resultset only.No concatenation would be required.
"Aaron Bertrand [SQL Server MVP]" wrote:

> Perform concatenation at the client / presentation layer?
>
>
>
>|||SQL Server is not a text/image editor. If your content can easily be
concatenated, why is it not stored in one piece?
You could create a temporary table, and then use READTEXT/UPDATETEXT to
concatenate the values in SQL. This can hardly perform as well as a client
application.
ML
http://milambda.blogspot.com/

Returning fields from proc using dyn. SQL

doesnt work.
This i a testquestion to look att the behaviour:
CREATE PROCEDURE sp_testingReportsDeleteThis (@.arg1 varchar(100))
AS
declare @.sqlString varchar(800)
set @.sqlString = "select firstname from tbl_personalData where firstname
like '" +@.arg1 +"'"
execute (@.sqlString )
GO
Hoping for this proc to return "firstname" when executing this as a proc
with the command type set to Stored Proc...
The report designer asks me for the @.arg1 no problem, the result of testing
this syntax in "dataview" is exactly as expected. getting one col. full of
names like the name inserted in @.arg1 with the name "firstname". But the
fieldscolumn doesn't update.
I succeded once to get the fields-area updated, I don't know what I did, but
havent succeded since.
Whats missing, is this a "feature", or should I read the manuals one more
time'
PLS help me!!
regards
Kjell Brandes
PS.
I have to have this query dynamic, the above code is a sample to describe
the problem, not the actual productioncode...In this case you have the option of manually putting the field list in
(right mouse click where the fields should be listed, add field).
"Kjell Brandes" wrote:
> doesnt work.
> This i a testquestion to look att the behaviour:
> CREATE PROCEDURE sp_testingReportsDeleteThis (@.arg1 varchar(100))
> AS
> declare @.sqlString varchar(800)
> set @.sqlString = "select firstname from tbl_personalData where firstname
> like '" +@.arg1 +"'"
> execute (@.sqlString )
> GO
> Hoping for this proc to return "firstname" when executing this as a proc
> with the command type set to Stored Proc...
> The report designer asks me for the @.arg1 no problem, the result of testing
> this syntax in "dataview" is exactly as expected. getting one col. full of
> names like the name inserted in @.arg1 with the name "firstname". But the
> fieldscolumn doesn't update.
> I succeded once to get the fields-area updated, I don't know what I did, but
> havent succeded since.
> Whats missing, is this a "feature", or should I read the manuals one more
> time'
> PLS help me!!
> regards
> Kjell Brandes
> PS.
> I have to have this query dynamic, the above code is a sample to describe
> the problem, not the actual productioncode...
>
>|||I do not know if this will help... but a suggestion onthe SP... try
something like this..It's simpler and doesn't make a second batch
CREATE PROCEDURE sp_testingReportsDeleteThis (@.arg1 varchar(100))
AS
select firstname from tbl_personalData where firstname like @.arg1
GO
Wayne Snyder, MCDBA, SQL Server MVP
Mariner, Charlotte, NC
www.mariner-usa.com
(Please respond only to the newsgroups.)
I support the Professional Association of SQL Server (PASS) and it's
community of SQL Server professionals.
www.sqlpass.org
"Kjell Brandes" <kjell@.brandes.tv> wrote in message
news:ekT0VBnwEHA.2016@.TK2MSFTNGP15.phx.gbl...
> doesnt work.
> This i a testquestion to look att the behaviour:
> CREATE PROCEDURE sp_testingReportsDeleteThis (@.arg1 varchar(100))
> AS
> declare @.sqlString varchar(800)
> set @.sqlString = "select firstname from tbl_personalData where firstname
> like '" +@.arg1 +"'"
> execute (@.sqlString )
> GO
> Hoping for this proc to return "firstname" when executing this as a proc
> with the command type set to Stored Proc...
> The report designer asks me for the @.arg1 no problem, the result of
testing
> this syntax in "dataview" is exactly as expected. getting one col. full of
> names like the name inserted in @.arg1 with the name "firstname". But the
> fieldscolumn doesn't update.
> I succeded once to get the fields-area updated, I don't know what I did,
but
> havent succeded since.
> Whats missing, is this a "feature", or should I read the manuals one more
> time'
> PLS help me!!
> regards
> Kjell Brandes
> PS.
> I have to have this query dynamic, the above code is a sample to describe
> the problem, not the actual productioncode...
>
>

Returning Duplicate Records

I have a Transactions table w/the following columns (all VarChar):
CustomerID,
Customer_Name,
User_Name
And and Admin table w/the following columns (VarChar):
User_Name,
Company_ID
Now I want to return any records where the CustomerID is duplicated for
different Customer_Names when Grouped by Company_ID. Here's a sample of wha
t
the returned data will look like:
Company_ID Customer_ID Customer_Name
R9 321 Ted Smith
R9 321 Rob Wand
Here's my query:
SELECT COMPANY_ID, CUSTOMER_ID, CUSTOMER_NAME,
COUNT (CUSTOMER_ID) AS NUM_OCCUR
FROM TRANSACTIONS
INNER JOIN ADMIN ON
ADMIN.USER_NAME = TRANSACTIONS.USER_NAME
GROUP BY COMPANY_ID, CUSTOMER_NAME, CUSTOMER_ID
HAVING (COUNT (CUSTOMER_ID) > 1)
ORDER BY COMPANY_ID, CUSTOMER_ID, CUSTOMER_NAME
This query only gets me half way there, as I can only visually inspect
what's returned. Here's a sample of the returned data:
Company_ID Customer_ID Customer_Name Num_Occur
R12 1 Jim Jones 2
R9 1000 Chris B 3
R9 1000 Brian P 5
R9 1001 Dave B 8
In this example, I ONLY want to return records 2 & 3 where the Company_ID,
and Customer_ID are the same, but the Customer_Names differ.On Thu, 19 Jan 2006 08:07:03 -0800, Eric wrote:

>I have a Transactions table w/the following columns (all VarChar):
>CustomerID,
>Customer_Name,
>User_Name
>And and Admin table w/the following columns (VarChar):
>User_Name,
>Company_ID
>Now I want to return any records where the CustomerID is duplicated for
>different Customer_Names when Grouped by Company_ID. Here's a sample of wh
at
>the returned data will look like:
>Company_ID Customer_ID Customer_Name
>R9 321 Ted Smith
>R9 321 Rob Wand
>Here's my query:
>SELECT COMPANY_ID, CUSTOMER_ID, CUSTOMER_NAME,
> COUNT (CUSTOMER_ID) AS NUM_OCCUR
>FROM TRANSACTIONS
>INNER JOIN ADMIN ON
> ADMIN.USER_NAME = TRANSACTIONS.USER_NAME
>GROUP BY COMPANY_ID, CUSTOMER_NAME, CUSTOMER_ID
>HAVING (COUNT (CUSTOMER_ID) > 1)
>ORDER BY COMPANY_ID, CUSTOMER_ID, CUSTOMER_NAME
>This query only gets me half way there, as I can only visually inspect
>what's returned. Here's a sample of the returned data:
>Company_ID Customer_ID Customer_Name Num_Occur
>R12 1 Jim Jones 2
>R9 1000 Chris B 3
>R9 1000 Brian P 5
>R9 1001 Dave B 8
>In this example, I ONLY want to return records 2 & 3 where the Company_ID,
>and Customer_ID are the same, but the Customer_Names differ.
Hi Eric,
Try if this works for you:
SELECT a.Company_ID, t.CustomerID, t.Customer_Name
FROM Admin AS a
INNER JOIN Transactions AS t
ON t.User_Name = a.User_Name
WHERE EXISTS
(SELECT *
FROM Transactions AS t2
WHERE t2.CustomerID = t.CustomerID
AND t2.User_Name <> t.User_Name)
(untested - see www.aspfaq.com/5006 if you prefer a tested reply)
Hugo Kornelis, SQL Server MVP