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

Thursday, March 22, 2012

Can't seem to get the newly created entry's identity field :(

Hi there,

I have a stored procedure that executes a transaction which updates/inserts into a table on a remote server and should then use that new entry's autogenerated primary key to update another table.
I try to store that key into a variable called @.NewlyCreatedPastelDClinkNumber but to no avail

I have used the @.@.Identity approach and now try to manually get that key to from other information but still no go..My thinking is: since i am using transactions, maybe the entry cant be found until the transaction has been committed...but surely it should find it after the commit statement? Here is my code: I have marked the interesting bit with blue for simplicity.

ALTER procedure [dbo].[inv_SynchronizeClientsWithPastel]
as
BEGIN
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
SET XACT_ABORT ON

DECLARE @.PastelDCLinkNumber int
DECLARE @.ClientID int
DECLARE @.Name varchar(25)
DECLARE @.Surname nvarchar(25)
DECLARE @.POBoxAddr1 varchar(40)
DECLARE @.POBoxAddr2 varchar(40)
DECLARE @.PostalCode varchar(5)
DECLARE @.ClientCreditCardNumber nvarchar(50)
DECLARE @.NewlyCreatedPastelDClinkNumber int
DECLARE PastelClientPortCursor CURSOR FOR

SELECT id, [Name], Surname, POBoxAddr1, POBoxAddr2, PostalCode, PastelDCLinkNumber ,CreditCardNumber
FROM inc_Client
WHERE HasSynchronizedWithPastel = 0

OPEN PastelClientPortCursor;
FETCH NEXT FROM PastelClientPortCursor
INTO @.ClientID,@.Name,@.Surname,@.POBoxAddr1,@.POBoxAddr2,@.PostalCode,@.PastelDCLinkNumber,@.ClientCreditCardNumber
WHILE @.@.FETCH_STATUS = 0
BEGIN

--Step2 insert/update the client information into the Synergy invoice and client table
BEGIN TRANSACTION T1
IF Exists(SELECT DCLink from [server].[Satra Corporate (Pty) Ltd].dbo.Client WHERE DCLink = @.PastelDCLinkNumber)

--Update the Pastel Client table

Begin
Update [server].[Satra Corporate (Pty) Ltd].dbo.Client SET
Name = (@.Name + ' ' + @.Surname),
Account = (@.Name + ' ' + @.Surname),
Post1 = @.POBoxAddr1,
Post2 = @.POBoxAddr2,
PostPC = @.PostalCode,
cAccDescription = 'Credit Card Number: ' + @.ClientCreditCardNumber
WHERE DCLink = @.PastelDCLinkNumber
End

ELSE
Begin
--Insert into the Pastel Client table
INSERT INTO [server].[Satra Corporate (Pty) Ltd].dbo.Client
(Account, Name, Post1, Post2, PostPC, AccountTerms, CT, Credit_Limit,
RepID, Interest_Rate, Discount, On_Hold, BFOpenType, BankLink,
AutoDisc,
DiscMtrxRow, CashDebtor, DCBalance, CheckTerms, UseEmail,
iCountryID, cAccDescription, iCurrencyID, bStatPrint,
bStatEmail, bForCurAcc,
fForeignBalance, bTaxPrompt, iARPriceListNameID)
VALUES
(
SUBSTRING(@.Name, 1,19), --Account
(@.Name + ' ' + @.Surname), --Name
@.POBoxAddr1, --Post1
@.POBoxAddr2, --Post2
@.PostalCode, --PostPC
0, --Account_Terms
1, --CT
0,--Credit_Limit
0, --Rep_ID
0, --interest_Rate
0, --Discount
0, --On_Hold
0, --BFOpenType
0, --BankLink
0, --AutoDisc
0, --DiscMatrix
0, --CashDebtor
0, --DCBalance
1, --CheckTerms
0, --UseEmail
0, --iCountryID
'Credit Card Number: ' + @.ClientCreditCardNumber,
0, --iCurrencyID
1, --StatPrint
0, --StatEmail
0, --bForCurAcc
0, --ForeignBal
1, --bTaxPrompt
1 --iARPriceListNameID
)
End

--If the rowcount is 0, an error has occured
IF @.@.ROWCOUNT <> 0
Begin
COMMIT TRANSACTION T1
execute sec_LogSQLTransaction 'inv_SynchronizeClientsWithPastel' ,'inc_Client_id',@.ClientID,'System'
-- Step 3Update the HasSynchronizedWithPastel Flag

Begin
SET @.NewlyCreatedPastelDClinkNumber = (SELECT DCLink From [server].[Satra Corporate (Pty) Ltd].dbo.Client
WHERE Name = (@.Name + ' ' + @.Surname)AND
Account = (@.Name + ' ' + @.Surname)AND
Post1 = @.POBoxAddr1 AND
Post2 = @.POBoxAddr2 AND
PostPC = @.PostalCode AND
cAccDescription = 'Credit Card Number: ' + @.ClientCreditCardNumber)
End

Begin
Update inc_Client SET
HasSynchronizedWithPastel = 1 ,
PastelDCLinkNumber = @.NewlyCreatedPastelDClinkNumber
WHERE id = @.ClientID
End
End

--Rollback transaction
IF @.@.TRANCOUNT > 0
Begin
ROLLBACK TRANSACTION T1
execute sec_LogSQLTransactionError 'inv_SynchronizeClientsWithPastel','inc_Client_id',@.ClientID,'System'
End

FETCH NEXT FROM PastelClientPortCursor
INTO @.ClientID,@.Name,@.Surname,@.POBoxAddr1,@.POBoxAddr2,@.PostalCode,@.PastelDCLinkNumber, @.ClientCreditCardNumber
END
CLOSE PastelClientPortCursor;
DEALLOCATE PastelClientPortCursor;

END

SET XACT_ABORT OFF
Go

Instead of:

COMMIT TRANSACTION T1
execute sec_LogSQLTransaction 'inv_SynchronizeClientsWithPastel' ,'inc_Client_id',@.ClientID,'System'
-- Step 3Update the HasSynchronizedWithPastel Flag

Begin
SET @.NewlyCreatedPastelDClinkNumber = (SELECT DCLink From [server].[Satra Corporate (Pty) Ltd].dbo.Client
WHERE Name = (@.Name + ' ' + @.Surname)AND
Account = (@.Name + ' ' + @.Surname)AND
Post1 = @.POBoxAddr1 AND
Post2 = @.POBoxAddr2 AND
PostPC = @.PostalCode AND
cAccDescription = 'Credit Card Number: ' + @.ClientCreditCardNumber)
End

Try:

COMMIT TRANSACTION T1

SET @.NewlyCreatedPastelDClinkNumber = scope_identity()

execute sec_LogSQLTransaction 'inv_SynchronizeClientsWithPastel' ,'inc_Client_id',@.ClientID,'System'
-- Step 3Update the HasSynchronizedWithPastel Flag


|||

Problem 1)

IF Exists(SELECT DCLink from [server].[Satra Corporate (Pty) Ltd].dbo.Client WHERE DCLink = @.PastelDCLinkNumber)

--Update the Pastel Client table

Begin
Update [server].[Satra Corporate (Pty) Ltd].dbo.Client SET

Don't check for the data and then do the update. Simply DO the update first. If you update 0 rows, then you do the insert. This cuts exection in half when there is an update to be performed.

Problem 2)

IMMEDIATELY after the INSERT, put the @.@.ERROR and @.@.ROWCOUNT AND scope_identity() values into a variable. Then act on those three in appropriate order.

Problem 3)

You should use a remote sproc to do the update/insert stuff on the remote server. MUCH more efficient. Pass parameters in and then local stuff does work with a cached query plan and only one network trip.

|||Thanks for all your support. I'm going to give this a try|||Thank you for all your help. It worked.

I looked at your suggestions in your steps(problems) and immediately saw the advantages of your suggestions.

I will now adapt future stored procedure's templates to include those good practices. Thanks once more.

Regards
Mike

Can't seem to get the newly created entry's identity field :(

Hi there,

I have a stored procedure that executes a transaction which updates/inserts into a table on a remote server and should then use that new entry's autogenerated primary key to update another table.
I try to store that key into a variable called @.NewlyCreatedPastelDClinkNumber but to no avail

I have used the @.@.Identity approach and now try to manually get that key to from other information but still no go..My thinking is: since i am using transactions, maybe the entry cant be found until the transaction has been committed...but surely it should find it after the commit statement? Here is my code: I have marked the interesting bit with blue for simplicity.

ALTER procedure [dbo].[inv_SynchronizeClientsWithPastel]
as
BEGIN
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
SET XACT_ABORT ON

DECLARE @.PastelDCLinkNumber int
DECLARE @.ClientID int
DECLARE @.Name varchar(25)
DECLARE @.Surname nvarchar(25)
DECLARE @.POBoxAddr1 varchar(40)
DECLARE @.POBoxAddr2 varchar(40)
DECLARE @.PostalCode varchar(5)
DECLARE @.ClientCreditCardNumber nvarchar(50)
DECLARE @.NewlyCreatedPastelDClinkNumber int
DECLARE PastelClientPortCursor CURSOR FOR

SELECT id, [Name], Surname, POBoxAddr1, POBoxAddr2, PostalCode, PastelDCLinkNumber ,CreditCardNumber
FROM inc_Client
WHERE HasSynchronizedWithPastel = 0

OPEN PastelClientPortCursor;
FETCH NEXT FROM PastelClientPortCursor
INTO @.ClientID,@.Name,@.Surname,@.POBoxAddr1,@.POBoxAddr2,@.PostalCode,@.PastelDCLinkNumber,@.ClientCreditCardNumber
WHILE @.@.FETCH_STATUS = 0
BEGIN

--Step2 insert/update the client information into the Synergy invoice and client table
BEGIN TRANSACTION T1
IF Exists(SELECT DCLink from [server].[Satra Corporate (Pty) Ltd].dbo.Client WHERE DCLink = @.PastelDCLinkNumber)

--Update the Pastel Client table

Begin
Update [server].[Satra Corporate (Pty) Ltd].dbo.Client SET
Name = (@.Name + ' ' + @.Surname),
Account = (@.Name + ' ' + @.Surname),
Post1 = @.POBoxAddr1,
Post2 = @.POBoxAddr2,
PostPC = @.PostalCode,
cAccDescription = 'Credit Card Number: ' + @.ClientCreditCardNumber
WHERE DCLink = @.PastelDCLinkNumber
End

ELSE
Begin
--Insert into the Pastel Client table
INSERT INTO [server].[Satra Corporate (Pty) Ltd].dbo.Client
(Account, Name, Post1, Post2, PostPC, AccountTerms, CT, Credit_Limit,
RepID, Interest_Rate, Discount, On_Hold, BFOpenType, BankLink,
AutoDisc,
DiscMtrxRow, CashDebtor, DCBalance, CheckTerms, UseEmail,
iCountryID, cAccDescription, iCurrencyID, bStatPrint,
bStatEmail, bForCurAcc,
fForeignBalance, bTaxPrompt, iARPriceListNameID)
VALUES
(
SUBSTRING(@.Name, 1,19), --Account
(@.Name + ' ' + @.Surname), --Name
@.POBoxAddr1, --Post1
@.POBoxAddr2, --Post2
@.PostalCode, --PostPC
0, --Account_Terms
1, --CT
0,--Credit_Limit
0, --Rep_ID
0, --interest_Rate
0, --Discount
0, --On_Hold
0, --BFOpenType
0, --BankLink
0, --AutoDisc
0, --DiscMatrix
0, --CashDebtor
0, --DCBalance
1, --CheckTerms
0, --UseEmail
0, --iCountryID
'Credit Card Number: ' + @.ClientCreditCardNumber,
0, --iCurrencyID
1, --StatPrint
0, --StatEmail
0, --bForCurAcc
0, --ForeignBal
1, --bTaxPrompt
1 --iARPriceListNameID
)
End

--If the rowcount is 0, an error has occured
IF @.@.ROWCOUNT <> 0
Begin
COMMIT TRANSACTION T1
execute sec_LogSQLTransaction 'inv_SynchronizeClientsWithPastel' ,'inc_Client_id',@.ClientID,'System'
-- Step 3Update the HasSynchronizedWithPastel Flag

Begin
SET @.NewlyCreatedPastelDClinkNumber = (SELECT DCLink From [server].[Satra Corporate (Pty) Ltd].dbo.Client
WHERE Name = (@.Name + ' ' + @.Surname)AND
Account = (@.Name + ' ' + @.Surname)AND
Post1 = @.POBoxAddr1 AND
Post2 = @.POBoxAddr2 AND
PostPC = @.PostalCode AND
cAccDescription = 'Credit Card Number: ' + @.ClientCreditCardNumber)
End

Begin
Update inc_Client SET
HasSynchronizedWithPastel = 1 ,
PastelDCLinkNumber = @.NewlyCreatedPastelDClinkNumber
WHERE id = @.ClientID
End
End

--Rollback transaction
IF @.@.TRANCOUNT > 0
Begin
ROLLBACK TRANSACTION T1
execute sec_LogSQLTransactionError 'inv_SynchronizeClientsWithPastel','inc_Client_id',@.ClientID,'System'
End

FETCH NEXT FROM PastelClientPortCursor
INTO @.ClientID,@.Name,@.Surname,@.POBoxAddr1,@.POBoxAddr2,@.PostalCode,@.PastelDCLinkNumber, @.ClientCreditCardNumber
END
CLOSE PastelClientPortCursor;
DEALLOCATE PastelClientPortCursor;

END

SET XACT_ABORT OFF
Go

Instead of:

COMMIT TRANSACTION T1
execute sec_LogSQLTransaction 'inv_SynchronizeClientsWithPastel' ,'inc_Client_id',@.ClientID,'System'
-- Step 3Update the HasSynchronizedWithPastel Flag

Begin
SET @.NewlyCreatedPastelDClinkNumber = (SELECT DCLink From [server].[Satra Corporate (Pty) Ltd].dbo.Client
WHERE Name = (@.Name + ' ' + @.Surname)AND
Account = (@.Name + ' ' + @.Surname)AND
Post1 = @.POBoxAddr1 AND
Post2 = @.POBoxAddr2 AND
PostPC = @.PostalCode AND
cAccDescription = 'Credit Card Number: ' + @.ClientCreditCardNumber)
End

Try:

COMMIT TRANSACTION T1

SET @.NewlyCreatedPastelDClinkNumber = scope_identity()

execute sec_LogSQLTransaction 'inv_SynchronizeClientsWithPastel' ,'inc_Client_id',@.ClientID,'System'
-- Step 3Update the HasSynchronizedWithPastel Flag


|||

Problem 1)

IF Exists(SELECT DCLink from [server].[Satra Corporate (Pty) Ltd].dbo.Client WHERE DCLink = @.PastelDCLinkNumber)

--Update the Pastel Client table

Begin
Update [server].[Satra Corporate (Pty) Ltd].dbo.Client SET

Don't check for the data and then do the update. Simply DO the update first. If you update 0 rows, then you do the insert. This cuts exection in half when there is an update to be performed.

Problem 2)

IMMEDIATELY after the INSERT, put the @.@.ERROR and @.@.ROWCOUNT AND scope_identity() values into a variable. Then act on those three in appropriate order.

Problem 3)

You should use a remote sproc to do the update/insert stuff on the remote server. MUCH more efficient. Pass parameters in and then local stuff does work with a cached query plan and only one network trip.

|||Thanks for all your support. I'm going to give this a try|||Thank you for all your help. It worked.

I looked at your suggestions in your steps(problems) and immediately saw the advantages of your suggestions.

I will now adapt future stored procedure's templates to include those good practices. Thanks once more.

Regards
Mikesql

Can''t seem to get the newly created entry''s identity field :(

Hi there,

I have a stored procedure that executes a transaction which updates/inserts into a table on a remote server and should then use that new entry's autogenerated primary key to update another table.
I try to store that key into a variable called @.NewlyCreatedPastelDClinkNumber but to no avail

I have used the @.@.Identity approach and now try to manually get that key to from other information but still no go..My thinking is: since i am using transactions, maybe the entry cant be found until the transaction has been committed...but surely it should find it after the commit statement? Here is my code: I have marked the interesting bit with blue for simplicity.

ALTER procedure [dbo].[inv_SynchronizeClientsWithPastel]
as
BEGIN
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
SET XACT_ABORT ON

DECLARE @.PastelDCLinkNumber int
DECLARE @.ClientID int
DECLARE @.Name varchar(25)
DECLARE @.Surname nvarchar(25)
DECLARE @.POBoxAddr1 varchar(40)
DECLARE @.POBoxAddr2 varchar(40)
DECLARE @.PostalCode varchar(5)
DECLARE @.ClientCreditCardNumber nvarchar(50)
DECLARE @.NewlyCreatedPastelDClinkNumber int
DECLARE PastelClientPortCursor CURSOR FOR

SELECT id, [Name], Surname, POBoxAddr1, POBoxAddr2, PostalCode, PastelDCLinkNumber ,CreditCardNumber
FROM inc_Client
WHERE HasSynchronizedWithPastel = 0

OPEN PastelClientPortCursor;
FETCH NEXT FROM PastelClientPortCursor
INTO @.ClientID,@.Name,@.Surname,@.POBoxAddr1,@.POBoxAddr2,@.PostalCode,@.PastelDCLinkNumber,@.ClientCreditCardNumber
WHILE @.@.FETCH_STATUS = 0
BEGIN

--Step2 insert/update the client information into the Synergy invoice and client table
BEGIN TRANSACTION T1
IF Exists(SELECT DCLink from [server].[Satra Corporate (Pty) Ltd].dbo.Client WHERE DCLink = @.PastelDCLinkNumber)

--Update the Pastel Client table

Begin
Update [server].[Satra Corporate (Pty) Ltd].dbo.Client SET
Name = (@.Name + ' ' + @.Surname),
Account = (@.Name + ' ' + @.Surname),
Post1 = @.POBoxAddr1,
Post2 = @.POBoxAddr2,
PostPC = @.PostalCode,
cAccDescription = 'Credit Card Number: ' + @.ClientCreditCardNumber
WHERE DCLink = @.PastelDCLinkNumber
End

ELSE
Begin
--Insert into the Pastel Client table
INSERT INTO [server].[Satra Corporate (Pty) Ltd].dbo.Client
(Account, Name, Post1, Post2, PostPC, AccountTerms, CT, Credit_Limit,
RepID, Interest_Rate, Discount, On_Hold, BFOpenType, BankLink,
AutoDisc,
DiscMtrxRow, CashDebtor, DCBalance, CheckTerms, UseEmail,
iCountryID, cAccDescription, iCurrencyID, bStatPrint,
bStatEmail, bForCurAcc,
fForeignBalance, bTaxPrompt, iARPriceListNameID)
VALUES
(
SUBSTRING(@.Name, 1,19), --Account
(@.Name + ' ' + @.Surname), --Name
@.POBoxAddr1, --Post1
@.POBoxAddr2, --Post2
@.PostalCode, --PostPC
0, --Account_Terms
1, --CT
0,--Credit_Limit
0, --Rep_ID
0, --interest_Rate
0, --Discount
0, --On_Hold
0, --BFOpenType
0, --BankLink
0, --AutoDisc
0, --DiscMatrix
0, --CashDebtor
0, --DCBalance
1, --CheckTerms
0, --UseEmail
0, --iCountryID
'Credit Card Number: ' + @.ClientCreditCardNumber,
0, --iCurrencyID
1, --StatPrint
0, --StatEmail
0, --bForCurAcc
0, --ForeignBal
1, --bTaxPrompt
1 --iARPriceListNameID
)
End

--If the rowcount is 0, an error has occured
IF @.@.ROWCOUNT <> 0
Begin
COMMIT TRANSACTION T1
execute sec_LogSQLTransaction 'inv_SynchronizeClientsWithPastel' ,'inc_Client_id',@.ClientID,'System'
-- Step 3Update the HasSynchronizedWithPastel Flag

Begin
SET @.NewlyCreatedPastelDClinkNumber = (SELECT DCLink From [server].[Satra Corporate (Pty) Ltd].dbo.Client
WHERE Name = (@.Name + ' ' + @.Surname)AND
Account = (@.Name + ' ' + @.Surname)AND
Post1 = @.POBoxAddr1 AND
Post2 = @.POBoxAddr2 AND
PostPC = @.PostalCode AND
cAccDescription = 'Credit Card Number: ' + @.ClientCreditCardNumber)
End

Begin
Update inc_Client SET
HasSynchronizedWithPastel = 1 ,
PastelDCLinkNumber = @.NewlyCreatedPastelDClinkNumber
WHERE id = @.ClientID
End
End

--Rollback transaction
IF @.@.TRANCOUNT > 0
Begin
ROLLBACK TRANSACTION T1
execute sec_LogSQLTransactionError 'inv_SynchronizeClientsWithPastel','inc_Client_id',@.ClientID,'System'
End

FETCH NEXT FROM PastelClientPortCursor
INTO @.ClientID,@.Name,@.Surname,@.POBoxAddr1,@.POBoxAddr2,@.PostalCode,@.PastelDCLinkNumber, @.ClientCreditCardNumber
END
CLOSE PastelClientPortCursor;
DEALLOCATE PastelClientPortCursor;

END

SET XACT_ABORT OFF
Go

Instead of:

COMMIT TRANSACTION T1
execute sec_LogSQLTransaction 'inv_SynchronizeClientsWithPastel' ,'inc_Client_id',@.ClientID,'System'
-- Step 3Update the HasSynchronizedWithPastel Flag

Begin
SET @.NewlyCreatedPastelDClinkNumber = (SELECT DCLink From [server].[Satra Corporate (Pty) Ltd].dbo.Client
WHERE Name = (@.Name + ' ' + @.Surname)AND
Account = (@.Name + ' ' + @.Surname)AND
Post1 = @.POBoxAddr1 AND
Post2 = @.POBoxAddr2 AND
PostPC = @.PostalCode AND
cAccDescription = 'Credit Card Number: ' + @.ClientCreditCardNumber)
End

Try:

COMMIT TRANSACTION T1

SET @.NewlyCreatedPastelDClinkNumber = scope_identity()

execute sec_LogSQLTransaction 'inv_SynchronizeClientsWithPastel' ,'inc_Client_id',@.ClientID,'System'
-- Step 3Update the HasSynchronizedWithPastel Flag


|||

Problem 1)

IF Exists(SELECT DCLink from [server].[Satra Corporate (Pty) Ltd].dbo.Client WHERE DCLink = @.PastelDCLinkNumber)

--Update the Pastel Client table

Begin
Update [server].[Satra Corporate (Pty) Ltd].dbo.Client SET

Don't check for the data and then do the update. Simply DO the update first. If you update 0 rows, then you do the insert. This cuts exection in half when there is an update to be performed.

Problem 2)

IMMEDIATELY after the INSERT, put the @.@.ERROR and @.@.ROWCOUNT AND scope_identity() values into a variable. Then act on those three in appropriate order.

Problem 3)

You should use a remote sproc to do the update/insert stuff on the remote server. MUCH more efficient. Pass parameters in and then local stuff does work with a cached query plan and only one network trip.

|||Thanks for all your support. I'm going to give this a try|||Thank you for all your help. It worked.

I looked at your suggestions in your steps(problems) and immediately saw the advantages of your suggestions.

I will now adapt future stored procedure's templates to include those good practices. Thanks once more.

Regards
Mike

Tuesday, March 20, 2012

Cant see stored procedures

Hi,

Can anyone help me. I've created a stored procedure in sql server and I'm trying to run it from my asp.net page. On Database Explorer I can't see it, or any for that matter, however I can see tables in the same schema.

Also I can't see it when I build a table adapter either.

Can anybody help?

Thanks

Sam

My first suspicion is that you didn't succeed in creating the stored procedure as you think you have done. To allay that suspicion, can you see the proc in Sql Server Management Studio?

|||

Yes I can see it and execute it, it works fine through sql server

I'm thinking that it might be because I'm using the express versions of the software sql server studio and visual web developer. Do you think that might be limiting the functionality?

|||

No. That wouldn't limit what you can see in the Database explorer. I've just attached Northwind to SqlExpress, and can see the procs, views etc in DataBase Explorer in VWD.

Try clicking the Refresh button at the top of the Database Explorer panel.


|||

check you master database mybe you created it in default database which is usual master when you open New Query window.If it is true put line below on top of your proceureUSE [DATABASE NAME] GO

|||

As JPazgier mentioned you probably created the proc in the default master db. If so, script out the proc, drop the proc from master db, re-create it in the actual db. If that is not the case and the proc is already in the right database, then check your connection string to see if your application is connecting to the right database.

Can't see stored proc results

I have this stored proc:

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go

ALTER PROCEDURE [dbo].[usp_CrimRecTest]
-- Add the parameters for the stored procedure here
@.caseID [nvarchar]

AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

-- Insert statements for procedure here
SELECT dbo.tblCASENOMASTER.CASENO, dbo.tblCASEMAST.LASTNAME, dbo.tblCASEMAST.FRSTNAME
FROM dbo.tblCASENOMASTER LEFT OUTER JOIN
dbo.tblCASEMAST ON dbo.tblCASENOMASTER.CASENO = dbo.tblCASEMAST.CASENO
WHERE (dbo.tblCASENOMASTER.CASENO = @.caseID)
END

When I run this with an EXEC statement, the result pane shows no results but the message pane says it completed successfully and one row is affected. I know my input data is good. I also get nothing when I call this sproc from a VB front end. Any ideas?

Thanks.

What did you mean by --Insert statements for procedure here ? Is there something which you commented out for posting here ? The insert can prdouce x rows affected also as the Select part can. So the insert suceeded with X rows, but the query didn′t bring back any results.

HTH, Jens Suessmeyer.

http://www.sqlserver2005.de
|||All comment lines in this post are from the template produced when I created the sproc in SQL Server 2005. The code posted is copied directly from my sproc - nothing deleted, altered or commented out.|||

I found the problem.

@.caseID [nvarchar] was changed to:

@.caseID nvarchar(12)

This ran correctly.

Thanks for your reply Jens.

can't see print messages during the running a of stored procedure

I have a stored procedure running from Query Analyzer that runs for a long
time and would like to have status messages print out during the procedure.
They all seem to come when the procedure is complete - is there any way to
have them print while it is running. I 've actually tried having the main
SP call a smaller SP with prints, but they don't come out till the end as
well.
Help to a new Transact SQL writer,
Thanks
TW
TW,
I don't know how to do just what you want, but you could try pumping your
messages into a trace table. Then you could query that table while the
long-running stored procedure continues. Transaction isolation levels would
affect how this works for you.
Russell Fields
"Weave" <tweaver60@.suscom.net> wrote in message
news:10apu6dm256v76@.corp.supernews.com...
> I have a stored procedure running from Query Analyzer that runs for a long
> time and would like to have status messages print out during the
procedure.
> They all seem to come when the procedure is complete - is there any way to
> have them print while it is running. I 've actually tried having the main
> SP call a smaller SP with prints, but they don't come out till the end as
> well.
> Help to a new Transact SQL writer,
> Thanks
> TW
>
|||You could use RAISERROR and the NOWAIT option instead of PRINT.
Tibor Karaszi, SQL Server MVP
http://www.karaszi.com/sqlserver/default.asp
http://www.solidqualitylearning.com/
"Weave" <tweaver60@.suscom.net> wrote in message news:10apu6dm256v76@.corp.supernews.com...
> I have a stored procedure running from Query Analyzer that runs for a long
> time and would like to have status messages print out during the procedure.
> They all seem to come when the procedure is complete - is there any way to
> have them print while it is running. I 've actually tried having the main
> SP call a smaller SP with prints, but they don't come out till the end as
> well.
> Help to a new Transact SQL writer,
> Thanks
> TW
>

Cant see image

Hello, my image is stored on the database as an URL, not binary.

I put a textbox and the url is show on the report,

then I put an image and this expression

=(ReportItems!dslogo.Value)

dslogo is the name of the textbox where the url is. but I dont see my image yet.

Did you set the source property of the image to "External"? Do you get the image in designer preview?|||

Its external and no I dont see it in the preview neither,

when I copy paste the url in the browser it shows me the image.

|||

Hmm, I tried a simple repro and it worked just fine for me. Here is the rdl I used:

<?xml version="1.0" encoding="utf-8"?>
<Report xmlns="http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition" xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner">
<DataSources>
<DataSource Name="Northwind">
<DataSourceReference>Northwind</DataSourceReference>
<rd:DataSourceID>6865eece-7da0-4cf5-9a9f-0f9d8d019185</rd:DataSourceID>
</DataSource>
</DataSources>
<BottomMargin>1in</BottomMargin>
<RightMargin>1in</RightMargin>
<rd:DrawGrid>true</rd:DrawGrid>
<InteractiveWidth>8.5in</InteractiveWidth>
<rd:SnapToGrid>true</rd:SnapToGrid>
<Body>
<ReportItems>
<Image Name="image1">
<Sizing>AutoSize</Sizing>
<Left>2.125in</Left>
<MIMEType />
<Top>1.25in</Top>
<ZIndex>1</ZIndex>
<Width>1.22917in</Width>
<Source>External</Source>
<Style />
<Height>0.36458in</Height>
<Value>=ReportItems!ID.Value</Value>
</Image>
<Textbox Name="ID">
<Left>2.125in</Left>
<Top>0.5in</Top>
<rd:DefaultName>ID</rd:DefaultName>
<Width>1in</Width>
<Style>
<PaddingLeft>2pt</PaddingLeft>
<PaddingBottom>2pt</PaddingBottom>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
</Style>
<CanGrow>true</CanGrow>
<Height>0.25in</Height>
<Value>=Fields!ID.Value</Value>
</Textbox>
</ReportItems>
<Height>3.75in</Height>
</Body>
<rd:ReportID>689d4b94-4437-47b2-b266-840ecd5d2866</rd:ReportID>
<LeftMargin>1in</LeftMargin>
<DataSets>
<DataSet Name="DataSet1">
<Query>
<rd:UseGenericDesigner>true</rd:UseGenericDesigner>
<CommandText>select 'http://hp.msn.com/global/c/lg/msft94.gif'</CommandText>
<DataSourceName>Northwind</DataSourceName>
</Query>
<Fields>
<Field Name="ID">
<rd:TypeName>System.String</rd:TypeName>
<DataField />
</Field>
</Fields>
</DataSet>
</DataSets>
<Width>12.875in</Width>
<InteractiveHeight>11in</InteractiveHeight>
<Language>en-US</Language>
<TopMargin>1in</TopMargin>
</Report>

|||

The reporting server is in another server than my machine, the image is on the reporting service but I am testing the report from the preview tab. Maybe it fails because the image is on another server and the report is not deployed?

The image is inside a folder of a web application

C:\Inetpub\wwwroot\Application\images\image1.gif.

Does the folder need special permissions, or do I have to configure reportserver XML configuration files to execute on another context?

Thanks

Monday, March 19, 2012

Cant save my stored procedure using VS2005

Hi!

I'm using VS2005 and trying to save my very simple stored procedure.
The error message "Invalid object name 'dbo.xxxxx' just pop's up.

The SP is written through the Server Explorer > Stored Procedures > Add new... etc.
Using SQL server 2000.

Don't think this has to do with the SP-code but here it is:

ALTER PROCEDUREdbo.KontrollUnikPersNr
@.PersNrnvarchar(50) =null OUTPUT
AS
SELECT@.PersNr = PersNrFROMUserWHEREPersNr = @.PersNr
RETURN@.@.ROWCOUNT

Thanx i advance for any help!

Looks like you are trying to ALTER a proc that does not exist. Try changing the ALTER to CREATE and see if it helps.

Also, I dont understand what you are trying to return from the stored proc - the rowcount or the value from the database?

|||

Thanx a lot!

I changed the Alter to Create and it works... didn't have to think of the in VS2003.

I'm returning the rowcount to see if there is any Users with the specific values that has to be unique in my user database table.

Thanks a lot again!Smile

|||

If you just need the count you could do it like this:

ALTER PROCEDURE dbo.KontrollUnikPersNr@.PersNrvarchar(50) =NULL,@.countint OUTPUTASBEGINSET NOCOUNT ONSELECT @.count =count(*)FROMUserWHERE PersNr = @.PersNrSET NOCOUNT OFFEND

|||

Hm, did'nt think of that... nice.

Thanx a lot again... let me know if I can help you with any tricky stuff.. erhm... Wink

Can't run Stored Procedure

I am trying to run a stored procedure from an SQL task:

First, here is the proc (execs fine in : SSMS query)

CREATE PROC [dbo].[sp_Hist_Max_Dates]

@.Interval varchar(8),

@.Name1 varchar(32),

@.Max_Date datetime OUTPUT

AS

IF @.Interval = 'd'

BEGIN

SELECT @.Max_Date = MAX(Max_Daily_Date) FROM SiteTable WHERE Site_Name = @.Name1

END

ELSE IF @.Interval = 'm'

BEGIN

SELECT @.Max_Date = MAX(Max_Monthly_Date) FROM SIteTable WHERE SIte_Name = @.Name1

END

Here is the call from the Execute SQL Task:

EXEC sp_Hist_Max_Dates ?, ?, ? OUTPUT

Here are how the parameters are defined in the Execute SQL Task:

gv_VarInterval INPUT varchar 0

gv_Name1 INPUT varchar 1

gv_MaxDate OUTPUT datetime 2

(Variables used as input parameters defined as strings with package scope)

Here is the error I am getting:

[Execute SQL Task] Error: Executing the query "EXEC dbo.sp_Hist_Max_Dates ?, ?, ? OUTPUT" failed with the following error: "Error HRESULT E_FAIL has been returned from a call to a COM component.". Possible failure reasons: Problems with the query, "ResultSet" property not set correctly, parameters not set correctly, or connection not established correctly.

The connection is just OLEDB to SQL Server 2005. Any ideas why is this not working?

Thanks!

Kayda

Try adding the parameter name (as declared in the SP) and the '=' sign to the SQL command:

EXEC sp_Hist_Max_Dates @.Parametername1 = ?,@.Parametername2= ?, @.Parametername3 = ? OUTPUT

|||another cryptic error message? hardly surprising... check if the account under which a package is run, has rights to execute the stored procedure|||On your SQL Task, set the "BypassPrepare" to TRUE. Otherwise the validation tries to validate the ?'s, and can't.

cant run stored procedure

I trying to move one of my queries to stored procedure, i use sql server 2005

i went to the database, choosed "programability> stored procedure" and the "new stored procedure.

this is what i got after changing the text:

set ANSI_NULLSONset QUOTED_IDENTIFIERONgo-- =============================================-- Author:<Author,,Name>-- Create date: <Create Date,,>-- Description:<Description,,>-- =============================================create PROCEDURE [ShoreshDBUser].[shoreshsearch]-- Add the parameters for the stored procedure here@.tablenamevarchar(50), @.startpointint, @.wordvarchar(50),@.order varchar(50)ASBEGIN-- SET NOCOUNT ON added to prevent extra result sets from-- interfering with SELECT statements.SET NOCOUNT ON;-- Insert statements for procedure hereSELECT L.*FROM (SELECT TOP (@.startpoint + 20) *FROM ShoreshDBUser.shoreshsearchWHERE FREETEXT (*, @.word)ORDER BY @.order desc) LLEFTJOIN (SELECT TOP (@.startpoint) *FROM ShoreshDBUser.shoreshsearchWHERE FREETEXT (*, @.word)ORDER BY @.order desc) RON L.id = R.idWHERE (R.idIsNULL)ORDER BY L.idEND
then i tried to run the procedure, i clicked "excute", enter the parameters, and i got error massege; Msg 208, Level 16, State 3, Procedure shoreshsearch, Line 19

Invalid object name 'ShoreshDBUser.shoreshsearch'.

i tried to call it from the asp.net code, but i get the same error: Invalid object name 'ShoreshDBUser.shoreshsearch'

but if i try to create new procedure in the same name, i get error massege: there is a object in that name.

i just can't understand what i do wrong... can any body help me?

The 2 part name means <objectOwner>.<objectName>. So by your script, SQL Server thinks [ShorehDbUser] is the owner of the object. Do you have any user with that name? Generally objects are prefixed with DBO as the owner. SO modify your proc to

CREATE PROCEDURE dbo.[shoreshsearch].

You might also want to drop the previous one, because you will end up with 2 procs - one with dbo as the owner and the other with [ShoreshDBUser] as the owner. This will further cause confusion to application or other users.

DROP PROC [ShoreshDBUser].[shoreshsearch] to drop the old one.

Sunday, March 11, 2012

Can't run SP with GETDATE()

I'm having a problem running this stored procedure that is supposed to count
the "Failed Domains" based on the beginning date and end date.
I'd like to simply run this sp with getdate()-2 and getdate-1, but when I
run this:
Exec dbo.PROC_SuccessCountByDate getdate()-1, (getdate()
I get the error
Server: Msg 170, Level 15, State 1, Line 1
Line 1: Incorrect syntax near ')'.
The Stored Procedure:
CREATE PROC PROC_SuccessCountByDate
@.begdate datetime,
@.enddate datetime
as
select count(domain_) as 'Failed Domain Count', T1m.domain_
from Table1 T1
join Table2 T2
on T2.memberid = T1.memberid_
where T2.completionstatusid in (301, 303)
and T2.finalattempt > @.begdate
and T2.finalattempt < @.enddate
group by T1.domain_
having count(domain_)>5
order by 'Failed Domain Count' descDeclare @.Today datetime
Declare @.Yesterday datetime
SET @.Today = Getdate()
SET @.Yesterday = DATEADD(dd,-1,Getdate())
Exec dbo.PROC_SuccessCountByDate @.Yesterday,@.Today
HTH, Jens SUessmeyer.
"savvy95" <savvy95@.discussions.microsoft.com> schrieb im Newsbeitrag
news:058453F4-9FE1-440E-ADB0-67D284B6957C@.microsoft.com...
> I'm having a problem running this stored procedure that is supposed to
> count
> the "Failed Domains" based on the beginning date and end date.
> I'd like to simply run this sp with getdate()-2 and getdate-1, but when I
> run this:
> Exec dbo.PROC_SuccessCountByDate getdate()-1, (getdate()
> I get the error
> Server: Msg 170, Level 15, State 1, Line 1
> Line 1: Incorrect syntax near ')'.
>
> The Stored Procedure:
> CREATE PROC PROC_SuccessCountByDate
> @.begdate datetime,
> @.enddate datetime
> as
> select count(domain_) as 'Failed Domain Count', T1m.domain_
> from Table1 T1
> join Table2 T2
> on T2.memberid = T1.memberid_
> where T2.completionstatusid in (301, 303)
> and T2.finalattempt > @.begdate
> and T2.finalattempt < @.enddate
> group by T1.domain_
> having count(domain_)>5
> order by 'Failed Domain Count' desc
>|||Yes, you can;t pass an "Expression". like [getdate() - 1], as a parameter
to a Stored Proc.
You can only pass constant values, or variables (either the variable value
or address)
So in your case, create a variable (Declare @.MyDateTime DateTime) and set
the value of that variableto getdate() - 1, and then make your call using th
e
variable...
Exec dbo.PROC_SuccessCountByDate @.MyDateTime, getdate()
And get rid of the extra parentheses after the comma
Exec dbo.PROC_SuccessCountByDate getdate()-1, (getdate()
"savvy95" wrote:

> I'm having a problem running this stored procedure that is supposed to cou
nt
> the "Failed Domains" based on the beginning date and end date.
> I'd like to simply run this sp with getdate()-2 and getdate-1, but when I
> run this:
> Exec dbo.PROC_SuccessCountByDate getdate()-1, (getdate()
> I get the error
> Server: Msg 170, Level 15, State 1, Line 1
> Line 1: Incorrect syntax near ')'.
>
> The Stored Procedure:
> CREATE PROC PROC_SuccessCountByDate
> @.begdate datetime,
> @.enddate datetime
> as
> select count(domain_) as 'Failed Domain Count', T1m.domain_
> from Table1 T1
> join Table2 T2
> on T2.memberid = T1.memberid_
> where T2.completionstatusid in (301, 303)
> and T2.finalattempt > @.begdate
> and T2.finalattempt < @.enddate
> group by T1.domain_
> having count(domain_)>5
> order by 'Failed Domain Count' desc
>|||declare @.bd datetime
declare @.ed datetime
set @.bd = dateadd(day, -1, getdate())
set @.ed = getdate()
Exec dbo.PROC_SuccessCountByDate @.bd, @.ed
...
AMB
"savvy95" wrote:

> I'm having a problem running this stored procedure that is supposed to cou
nt
> the "Failed Domains" based on the beginning date and end date.
> I'd like to simply run this sp with getdate()-2 and getdate-1, but when I
> run this:
> Exec dbo.PROC_SuccessCountByDate getdate()-1, (getdate()
> I get the error
> Server: Msg 170, Level 15, State 1, Line 1
> Line 1: Incorrect syntax near ')'.
>
> The Stored Procedure:
> CREATE PROC PROC_SuccessCountByDate
> @.begdate datetime,
> @.enddate datetime
> as
> select count(domain_) as 'Failed Domain Count', T1m.domain_
> from Table1 T1
> join Table2 T2
> on T2.memberid = T1.memberid_
> where T2.completionstatusid in (301, 303)
> and T2.finalattempt > @.begdate
> and T2.finalattempt < @.enddate
> group by T1.domain_
> having count(domain_)>5
> order by 'Failed Domain Count' desc
>|||This is why I love this community; so many willing to help. Thanks. All of
you had the same solution.
Thanks again
"Jens Sü?meyer" wrote:

> Declare @.Today datetime
> Declare @.Yesterday datetime
> SET @.Today = Getdate()
> SET @.Yesterday = DATEADD(dd,-1,Getdate())
> Exec dbo.PROC_SuccessCountByDate @.Yesterday,@.Today
> HTH, Jens SUessmeyer.
> "savvy95" <savvy95@.discussions.microsoft.com> schrieb im Newsbeitrag
> news:058453F4-9FE1-440E-ADB0-67D284B6957C@.microsoft.com...
>
>|||Perhaps one time there will be an issue which you can also solve in here...
:-)
"savvy95" <savvy95@.discussions.microsoft.com> schrieb im Newsbeitrag
news:0BA224B0-F049-4E46-8BBD-6113DCCAF216@.microsoft.com...
> This is why I love this community; so many willing to help. Thanks. All
> of
> you had the same solution.
> Thanks again
> "Jens Smeyer" wrote:
>|||i want to make SP that enters values into my table, which has the default
value of the date column to getdate
so, if i didn't enter a value it will take the default value of the column
how can i describe this in the sp declaration ?
my sp is as follows :
---
create procedure add_new_abstract
@.abs_name nvarchar(20) ,
@.id_reg nvarchar(10),
@.id_topic nvarchar(10),
@.id_stat nvarchar(10),
@.abst nvarchar(20) ,
@.job_id nvarchar(20),
@.date_abs datetime
as
insert abstract
values (cast(cast(rand()*9285 as int)as
nvarchar(10)),@.abs_name,@.id_reg,@.id_topi
c,@.id_stat,@.abst,@.job_id,@.date_abs)
go
---
so, when i execute it with the getdate() it raise the error specified in
this discussion
and when i neglect it so that it takes the value as the default value of the
column , it asks for it
so, how can i solve this ?
thanx for ur help
--
regards
Maidoo.
"Jens Sü?meyer" wrote:

> Perhaps one time there will be an issue which you can also solve in here..
.
> :-)
>
> "savvy95" <savvy95@.discussions.microsoft.com> schrieb im Newsbeitrag
> news:0BA224B0-F049-4E46-8BBD-6113DCCAF216@.microsoft.com...
>
>|||On Fri, 10 Jun 2005 10:59:27 -0700, maidoo wrote:

>i want to make SP that enters values into my table, which has the default
>value of the date column to getdate
>so, if i didn't enter a value it will take the default value of the column
>how can i describe this in the sp declaration ?
Hi maidoo,
Change your proc like this:
create procedure add_new_abstract
@.abs_name nvarchar(20) ,
@.id_reg nvarchar(10),
@.id_topic nvarchar(10),
@.id_stat nvarchar(10),
@.abst nvarchar(20) ,
@.job_id nvarchar(20),
@.date_abs datetime = null
as
insert abstract
values (cast(cast(rand()*9285 as int)as
nvarchar(10)),@.abs_name,@.id_reg,@.id_topi
c,@.id_stat,@.abst,@.job_id,
COALESCE(@.date_abs, CURRENT_TIMESTAMP))
go
Best, Hugo
--
(Remove _NO_ and _SPAM_ to get my e-mail address)|||create procedure add_new_abstract
@.abs_name nvarchar(20) ,
@.id_reg nvarchar(10),
@.id_topic nvarchar(10),
@.id_stat nvarchar(10),
@.abst nvarchar(20) ,
@.job_id nvarchar(20),
@.date_abs datetime
as
SET @.date_abs = ISNULL(@.date_abs, GETDATE())
insert abstract
values (cast(cast(rand()*9285 as int)as
nvarchar(10)),@.abs_name,@.id_reg,@.id_topi
c,@.id_stat,@.abst,@.job_id,@.date_abs)
go
--
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/
"maidoo" <maidooalex@.msn.com> wrote in message
news:B70444AF-0A65-416E-91DB-05E4D911809E@.microsoft.com...
>i want to make SP that enters values into my table, which has the default
> value of the date column to getdate
> so, if i didn't enter a value it will take the default value of the column
> how can i describe this in the sp declaration ?
> my sp is as follows :
> ---
> create procedure add_new_abstract
> @.abs_name nvarchar(20) ,
> @.id_reg nvarchar(10),
> @.id_topic nvarchar(10),
> @.id_stat nvarchar(10),
> @.abst nvarchar(20) ,
> @.job_id nvarchar(20),
> @.date_abs datetime
> as
> insert abstract
> values (cast(cast(rand()*9285 as int)as
> nvarchar(10)),@.abs_name,@.id_reg,@.id_topi
c,@.id_stat,@.abst,@.job_id,@.date_abs
)
> go
> ---
> so, when i execute it with the getdate() it raise the error specified in
> this discussion
> and when i neglect it so that it takes the value as the default value of
> the
> column , it asks for it
> so, how can i solve this ?
> thanx for ur help
> --
> regards
> Maidoo.
>
> "Jens Smeyer" wrote:
>

Can't run my scheduled job which accesses a linked server: other options?

I have a stored procedure in a database on a server, and this stored
procedure uses a linked server.
The login I was given is only granted DBO permissions on this database.
I am trying to set this up so that the above stored procedure runs once
per month, so I naturally tried to set up a Job which would do this.
I have discovered from another group that:
"You cannot access a linked server from a TSQL jobstep if you aren't
symin."
So: How can I automatically run this stored procedure once per month
under these conditions?
Thanks,
RyanIn SQL 2000, change the job owner to symin.
In SQL 2005, change the job security context.
Arnie Rowland, YACE*
"To be successful, your heart must accompany your knowledge."
*Yet Another certification Exam
<ryan_willow@.hotmail.com> wrote in message
news:1151015746.073933.305090@.r2g2000cwb.googlegroups.com...
>I have a stored procedure in a database on a server, and this stored
> procedure uses a linked server.
> The login I was given is only granted DBO permissions on this database.
> I am trying to set this up so that the above stored procedure runs once
> per month, so I naturally tried to set up a Job which would do this.
> I have discovered from another group that:
> "You cannot access a linked server from a TSQL jobstep if you aren't
> symin."
> So: How can I automatically run this stored procedure once per month
> under these conditions?
> Thanks,
> Ryan
>|||I'm in SQL 2000.
I cannot change the job owner because my permissions do not allow this.
Apparently a dbo user named 'User' can only create a job with owner
'User'. I am trying to implement this without having to step outside
my dbo security level. Is this going to be possible, and if so how?
Thanks.
Arnie Rowland wrote:
> In SQL 2000, change the job owner to symin.
> In SQL 2005, change the job security context.
> --
> Arnie Rowland, YACE*
> "To be successful, your heart must accompany your knowledge."
> *Yet Another certification Exam
>
> <ryan_willow@.hotmail.com> wrote in message
> news:1151015746.073933.305090@.r2g2000cwb.googlegroups.com...|||That will not be possible without coordination with the server
administrator. Since Jobs have the potential for significant performance
issues as well as security issues for the server, the security context for
Jobs is symin. (in SQL2000).
And of course a SQL Server Administrator is probably not going to allow you
to have permission to create or change a job because of the potential that
it could execute any code or activity under the symin security context.
Jobs are a 'Server' level activity -NOT a database level activity. Even if a
job is confined to a single database, it still operates as a server level
activity.
That changes with SQL 2005.
--
Arnie Rowland, YACE*
"To be successful, your heart must accompany your knowledge."
*Yet Another certification Exam
"Ryan" <ryan_willow@.hotmail.com> wrote in message
news:1151017863.128715.208750@.g10g2000cwb.googlegroups.com...
> I'm in SQL 2000.
> I cannot change the job owner because my permissions do not allow this.
> Apparently a dbo user named 'User' can only create a job with owner
> 'User'. I am trying to implement this without having to step outside
> my dbo security level. Is this going to be possible, and if so how?
> Thanks.
> Arnie Rowland wrote:
>|||Very informative, thanks Arnie.
Arnie Rowland wrote:
> That will not be possible without coordination with the server
> administrator. Since Jobs have the potential for significant performance
> issues as well as security issues for the server, the security context for
> Jobs is symin. (in SQL2000).
> And of course a SQL Server Administrator is probably not going to allow yo
u
> to have permission to create or change a job because of the potential that
> it could execute any code or activity under the symin security context.
> Jobs are a 'Server' level activity -NOT a database level activity. Even if
a
> job is confined to a single database, it still operates as a server level
> activity.
> That changes with SQL 2005.
> --
> Arnie Rowland, YACE*
> "To be successful, your heart must accompany your knowledge."
> *Yet Another certification Exam
>
> "Ryan" <ryan_willow@.hotmail.com> wrote in message
> news:1151017863.128715.208750@.g10g2000cwb.googlegroups.com...

Can't run my scheduled job which accesses a linked server: other options?

I have a stored procedure in a database on a server, and this stored
procedure uses a linked server.
The login I was given is only granted DBO permissions on this database.
I am trying to set this up so that the above stored procedure runs once
per month, so I naturally tried to set up a Job which would do this.
I have discovered from another group that:
"You cannot access a linked server from a TSQL jobstep if you aren't
sysadmin."
So: How can I automatically run this stored procedure once per month
under these conditions?
Thanks,
RyanIn SQL 2000, change the job owner to sysadmin.
In SQL 2005, change the job security context.
--
Arnie Rowland, YACE*
"To be successful, your heart must accompany your knowledge."
*Yet Another Certification Exam
<ryan_willow@.hotmail.com> wrote in message
news:1151015746.073933.305090@.r2g2000cwb.googlegroups.com...
>I have a stored procedure in a database on a server, and this stored
> procedure uses a linked server.
> The login I was given is only granted DBO permissions on this database.
> I am trying to set this up so that the above stored procedure runs once
> per month, so I naturally tried to set up a Job which would do this.
> I have discovered from another group that:
> "You cannot access a linked server from a TSQL jobstep if you aren't
> sysadmin."
> So: How can I automatically run this stored procedure once per month
> under these conditions?
> Thanks,
> Ryan
>|||I'm in SQL 2000.
I cannot change the job owner because my permissions do not allow this.
Apparently a dbo user named 'User' can only create a job with owner
'User'. I am trying to implement this without having to step outside
my dbo security level. Is this going to be possible, and if so how?
Thanks.
Arnie Rowland wrote:
> In SQL 2000, change the job owner to sysadmin.
> In SQL 2005, change the job security context.
> --
> Arnie Rowland, YACE*
> "To be successful, your heart must accompany your knowledge."
> *Yet Another Certification Exam
>
> <ryan_willow@.hotmail.com> wrote in message
> news:1151015746.073933.305090@.r2g2000cwb.googlegroups.com...
> >I have a stored procedure in a database on a server, and this stored
> > procedure uses a linked server.
> >
> > The login I was given is only granted DBO permissions on this database.
> >
> > I am trying to set this up so that the above stored procedure runs once
> > per month, so I naturally tried to set up a Job which would do this.
> >
> > I have discovered from another group that:
> > "You cannot access a linked server from a TSQL jobstep if you aren't
> > sysadmin."
> >
> > So: How can I automatically run this stored procedure once per month
> > under these conditions?
> >
> > Thanks,
> > Ryan
> >|||That will not be possible without coordination with the server
administrator. Since Jobs have the potential for significant performance
issues as well as security issues for the server, the security context for
Jobs is sysadmin. (in SQL2000).
And of course a SQL Server Administrator is probably not going to allow you
to have permission to create or change a job because of the potential that
it could execute any code or activity under the sysadmin security context.
Jobs are a 'Server' level activity -NOT a database level activity. Even if a
job is confined to a single database, it still operates as a server level
activity.
That changes with SQL 2005.
--
Arnie Rowland, YACE*
"To be successful, your heart must accompany your knowledge."
*Yet Another Certification Exam
"Ryan" <ryan_willow@.hotmail.com> wrote in message
news:1151017863.128715.208750@.g10g2000cwb.googlegroups.com...
> I'm in SQL 2000.
> I cannot change the job owner because my permissions do not allow this.
> Apparently a dbo user named 'User' can only create a job with owner
> 'User'. I am trying to implement this without having to step outside
> my dbo security level. Is this going to be possible, and if so how?
> Thanks.
> Arnie Rowland wrote:
>> In SQL 2000, change the job owner to sysadmin.
>> In SQL 2005, change the job security context.
>> --
>> Arnie Rowland, YACE*
>> "To be successful, your heart must accompany your knowledge."
>> *Yet Another Certification Exam
>>
>> <ryan_willow@.hotmail.com> wrote in message
>> news:1151015746.073933.305090@.r2g2000cwb.googlegroups.com...
>> >I have a stored procedure in a database on a server, and this stored
>> > procedure uses a linked server.
>> >
>> > The login I was given is only granted DBO permissions on this database.
>> >
>> > I am trying to set this up so that the above stored procedure runs once
>> > per month, so I naturally tried to set up a Job which would do this.
>> >
>> > I have discovered from another group that:
>> > "You cannot access a linked server from a TSQL jobstep if you aren't
>> > sysadmin."
>> >
>> > So: How can I automatically run this stored procedure once per month
>> > under these conditions?
>> >
>> > Thanks,
>> > Ryan
>> >
>|||Very informative, thanks Arnie.
Arnie Rowland wrote:
> That will not be possible without coordination with the server
> administrator. Since Jobs have the potential for significant performance
> issues as well as security issues for the server, the security context for
> Jobs is sysadmin. (in SQL2000).
> And of course a SQL Server Administrator is probably not going to allow you
> to have permission to create or change a job because of the potential that
> it could execute any code or activity under the sysadmin security context.
> Jobs are a 'Server' level activity -NOT a database level activity. Even if a
> job is confined to a single database, it still operates as a server level
> activity.
> That changes with SQL 2005.
> --
> Arnie Rowland, YACE*
> "To be successful, your heart must accompany your knowledge."
> *Yet Another Certification Exam
>
> "Ryan" <ryan_willow@.hotmail.com> wrote in message
> news:1151017863.128715.208750@.g10g2000cwb.googlegroups.com...
> > I'm in SQL 2000.
> >
> > I cannot change the job owner because my permissions do not allow this.
> > Apparently a dbo user named 'User' can only create a job with owner
> > 'User'. I am trying to implement this without having to step outside
> > my dbo security level. Is this going to be possible, and if so how?
> >
> > Thanks.
> >
> > Arnie Rowland wrote:
> >> In SQL 2000, change the job owner to sysadmin.
> >>
> >> In SQL 2005, change the job security context.
> >>
> >> --
> >> Arnie Rowland, YACE*
> >> "To be successful, your heart must accompany your knowledge."
> >>
> >> *Yet Another Certification Exam
> >>
> >>
> >> <ryan_willow@.hotmail.com> wrote in message
> >> news:1151015746.073933.305090@.r2g2000cwb.googlegroups.com...
> >> >I have a stored procedure in a database on a server, and this stored
> >> > procedure uses a linked server.
> >> >
> >> > The login I was given is only granted DBO permissions on this database.
> >> >
> >> > I am trying to set this up so that the above stored procedure runs once
> >> > per month, so I naturally tried to set up a Job which would do this.
> >> >
> >> > I have discovered from another group that:
> >> > "You cannot access a linked server from a TSQL jobstep if you aren't
> >> > sysadmin."
> >> >
> >> > So: How can I automatically run this stored procedure once per month
> >> > under these conditions?
> >> >
> >> > Thanks,
> >> > Ryan
> >> >
> >

Can't retrieve second resultset with jdbc sql server 2005 driver

Hi All,

My java application executes one stored procedure that returns two resultsets and then deal with data. The code actually is very simple

Statement stmt = con.createStatement(); con is database connection

ResultSet rs = stmt.getResultSet();

//Do something

rs.close();

rs = stmt.getResultSet();

//Do something

Then I got the error: The result set is closed.

The code worked well with jdbc sql server 2000 driver.

Thanks for your help.

Eric

Hello lxiao,

The syntax for getting the second result set is

if(stmt.getMoreResults())

stmt.getResultSet();

Keep in mind that the getMoreResults() methods takes multiple arguments which controls how visited result sets should persist. Those flags are:

CLOSE_CURRENT_RESULT

CLOSE_ALL_RESULTS

You can find more information about using multiple result sets objects at the following site http://msdn2.microsoft.com/en-us/library/ms378758.aspx

Regards,

Jaaved Mohammed

Can't retrieve second resultset with jdbc sql server 2005 driver

Hi All,

My java application executes one stored procedure that returns two resultsets and then deal with data. The code actually is very simple

Statement stmt = con.createStatement(); con is database connection

ResultSet rs = stmt.getResultSet();

//Do something

rs.close();

rs = stmt.getResultSet();

//Do something

Then I got the error: The result set is closed.

The code worked well with jdbc sql server 2000 driver.

Thanks for your help.

Eric

Hello lxiao,

The syntax for getting the second result set is

if(stmt.getMoreResults())

stmt.getResultSet();

Keep in mind that the getMoreResults() methods takes multiple arguments which controls how visited result sets should persist. Those flags are:

CLOSE_CURRENT_RESULT

CLOSE_ALL_RESULTS

You can find more information about using multiple result sets objects at the following site http://msdn2.microsoft.com/en-us/library/ms378758.aspx

Regards,

Jaaved Mohammed

Thursday, March 8, 2012

Can't remove SA account or delete xp_cmdshell ext stored proc?

I'm trying to make my SQL Server a tad more secure, but I'm unable to remove
SA (I'm running Mixed mode) -- can the SA account only be removed when using
windows Authentication? When I try to remove SA I get "selected user
cannot be dropped because the user owns objects". When I try to delect
xp_cmdshell I get the following error "You tried to delete one or more
system objects. They were not deleted."
I must admit, I'm a little confused, I'm trying to implement Microsofts
security recommendations, but either the documention is not
detailed/accurate or I'm missing something?
Any suggestions?
Thanks, Rob.Hi
You can not remove the SA account. Set a very complicated password for it,
write it down and put it in a safe.
For the xp_ look at
http://support.microsoft.com/defaul...kb;en-us;891984
Regards
--
Mike Epprecht, Microsoft SQL Server MVP
Zurich, Switzerland
MVP Program: http://www.microsoft.com/mvp
Blog: http://www.msmvps.com/epprecht/
"Rob R. Ainscough" wrote:

> I'm trying to make my SQL Server a tad more secure, but I'm unable to remo
ve
> SA (I'm running Mixed mode) -- can the SA account only be removed when usi
ng
> windows Authentication? When I try to remove SA I get "selected user
> cannot be dropped because the user owns objects". When I try to delect
> xp_cmdshell I get the following error "You tried to delete one or more
> system objects. They were not deleted."
> I must admit, I'm a little confused, I'm trying to implement Microsofts
> security recommendations, but either the documention is not
> detailed/accurate or I'm missing something?
> Any suggestions?
> Thanks, Rob.
>
>
>|||> I'm trying to make my SQL Server a tad more secure, but I'm unable to
> remove SA (I'm running Mixed mode) -- can the SA account only be removed
> when using windows Authentication? When I try to remove SA I get
> "selected user cannot be dropped because the user owns objects". When I
> try to delect xp_cmdshell I get the following error "You tried to delete
> one or more system objects. They were not deleted."
The sa login account cannot be deleted or renameed, nor it can't be revoked
any permission.

> I must admit, I'm a little confused, I'm trying to implement Microsofts
> security recommendations, but either the documention is not
> detailed/accurate or I'm missing something?
I don't think MS ever mentioned droping the sa account (as it can't be
done). Here are recommendations from Operations Guide: "
The sa account in a production environment should be given a complex
password, made up of uppercase and lowercase letters, symbols, spaces, and
numbers. The sa account should have a complex password, even if the SQL
Server is running in only Windows Authentication Mode. A complex password
protects SQL Server from someone easily getting administrative access to SQL
Server. This also protects the server in the event that an administrator
changes the security authentication mode to Mixed Mode.
Do not use the sa login account in a production environment. Instead, place
each DBA's network user account into a Windows group, create a single SQL
Server login account for the group then add the login account to the
sysadmin fixed server role. "
(http://www.microsoft.com/technet/pr...in/sqlops3.mspx
).
Dejan Sarka, SQL Server MVP
Associate Mentor
www.SolidQualityLearning.com|||Thank you for the information.
The book I was reading is Microsoft Press and the authors are Ed Robinson
and Michael James Bond.
I have the SA password complex so no worries there.
I guess I'll leave the xp_cmdshell alone as it seems to be more trouble that
it is worth to remove it.
Should I think about installing URLScan ?
"Dejan Sarka" <dejan_please_reply_to_newsgroups.sarka@.avtenta.si> wrote in
message news:%23BAAU89pFHA.3112@.TK2MSFTNGP12.phx.gbl...
> The sa login account cannot be deleted or renameed, nor it can't be
> revoked any permission.
>
> I don't think MS ever mentioned droping the sa account (as it can't be
> done). Here are recommendations from Operations Guide: "
> The sa account in a production environment should be given a complex
> password, made up of uppercase and lowercase letters, symbols, spaces, and
> numbers. The sa account should have a complex password, even if the SQL
> Server is running in only Windows Authentication Mode. A complex password
> protects SQL Server from someone easily getting administrative access to
> SQL Server. This also protects the server in the event that an
> administrator changes the security authentication mode to Mixed Mode.
> Do not use the sa login account in a production environment. Instead,
> place each DBA's network user account into a Windows group, create a
> single SQL Server login account for the group then add the login account
> to the sysadmin fixed server role. "
> (http://www.microsoft.com/technet/pr...ityLearning.com
>|||> Should I think about installing URLScan ?
Why don't you ask this in some IIS group, with explanation why do you think
you need it?
Dejan Sarka, SQL Server MVP
Associate Mentor
www.SolidQualityLearning.com

Wednesday, March 7, 2012

Cant quite figure this one out... any help?

I have 2 tables, one contains the details for all the documents stored on a server such as the documents name and which directory it is stored in, and the other contains the details for each document version (if there are any) these are paired up using the documents id, per example below

Documents
ID, Name, Dir
1, word.doc, /docs
2, excel.xls, /docs
3, webpage.html, /docs

Document Versions
ID
1
1
1
2
2
3

so, as you can see, in the versions table there are 3 versions of 'word.doc' 2 of 'excel.xls' and 1 of 'webpage.html'. i need to write a query that will return all the documents in the versions table who have a matching document in the documents table (that is not the major problem though) the main problem is that i only want to return it if the matching record in the documents table passes certain criteria, this being that it is from a certain site and has a particular type of file name. for example, i would like to return only the document versions whose parent records are '.doc' or '.xls' files, but not html. this would leave me with :

Versions
ID
1
1
1
2
2

leaving the last record out, as it's parent is a html file.

As a bonus, if you could tell me how to append the parents name to each record so i get a table like this :

Results
ID Name
1 'word.doc'
1 'word.doc'
1 'word.doc'
2 'excel.xls'
2 'excel.xls'

that would be great, thank youYou didn't specify database engine you use; but, in Oracle it would be something like this:SELECT d.id, d.name
FROM DOCUMENTS d, VERSIONS v
WHERE v.id = d.id
AND SUBSTR(d.name, INSTR(d.name, '.', 1) + 1, LENGTH(d.name)) <> 'html';
WHERE clause will be different for another requirements, of course.|||hmmm, not sure if that's quite it. and the database engine is SQL server|||As I can't see a generic SQL solution, I'd recommend using:SELECT d.id, d.name
FROM documents AS d
JOIN versions AS v
ON (v.id = d.id)
WHERE d.name NOT LIKE '%.html'-PatP|||Got It! Thanks for your help though. This was the final solution for anyone who's interested

SELECT Docs.Name, DocVersions.TimeCreated, DocVersions.Content
FROM DocVersions INNER JOIN
Docs ON DocVersions.Id = Docs.Id
WHERE (Docs.LeafName LIKE '%.doc' OR
Docs.Name LIKE '%.xls' OR
Docs.Name LIKE '%.ppt' OR
Docs.Name LIKE '%.pdf' OR
Docs.Name LIKE '%.mpp' OR
Docs.Name LIKE ' % .txt ') AND (Docs.DirName LIKE 'sites/archive/%')

I think i confused u all with my talk of leaving out the html document. It wasn't so much i wanted to leave that out as include the others if you know what i mean

Saturday, February 25, 2012

Cant pass search text into Stored Procedure

I am trying to inject dynamically generated text into a Sql2000 stored procedure. What am I doing wrong?
A code behind routine generates the following string value based on a visitor entering 'sail boats' in TextBox1. The routine splits the entry and creates the below string.

Companies.L_Keywords LIKE '%sail%' AND Companies.L_Keywords LIKE '%boats%'

I am trying to place this string result in the WHERE statement of a Sql2000 Stored Procedure using parameter @.VisitorKeywords.

PROCEDURE dbo.KWsearch
AS
SELECT DISTINCT Companies.L_Name, Companies.L_ID, Companies.L_Enabled
WHERE ( @.visitorKeywords ) AND (Companies.L_Enabled = 1)
ORDER BY Companies.L_Name

I am wanting the resulting WHERE portion to be:

WHERE ( Companies.L_Keywords LIKE '%sail%' AND Companies.L_Keywords LIKE '%boats%' ) AND (Companies.L_Enabled = 1)

Thank you

I noticed your starting character is '%something..'. Realize that this may not use any indexes on the L_Keywords column. Because your first character itself is a wildcard, SQL Server does not know where to start so it will not use the index. In order for indexes to be used the query should be like: 'something%'. Your query should look like this: Pass just the value to the proc. The value coming from your app for @.keyword1 would be '%sail%'.

SELECT DISTINCT Companies.L_Name, Companies.L_ID, Companies.L_EnabledWHERE ( Companies.L_KeywordsLIKE @.KeyWord1AND Companies.L_KeywordsLIKE @.KeyWord2 )AND (Companies.L_Enabled = 1)ORDER BY Companies.L_Name

|||

I was able to pass in the values but I need to pass in the entire string because the number of LIKE statements is determined by the number of keywords the user enters. If they enter "sail boats", I need two LIKE statements but if they enter "big blue sail boats" I need four LIKE statements. That is why I was trying to pass in the entire string.

|||

Is it possible to pass a partial SQL statement string into a stored procedure and concantenate it with the resident code using a parameter?

|||

Yes you'd have to use dynamic SQL. Check out this article before attempting to do so:http://www.sommarskog.se/dynamic_sql.html

|||

Below is the routine I am using to create the partial WHERE statement. Does it present a secuity risk? I assumed that programically generating the SELECT in this way would offer greatly improved security.

What I am trying to do is pass the strings produced by this routine into the Stored Procedure I use to access the database.

protectedvoid KeyWordSqlSelect()
{
kwdString = UserKeyword.Text;
Criteria1 ="";
Criteria2 ="";
string[] ArrKwdString = System.Text.RegularExpressions.Regex.Split(kwdString," ");
int iCount = 0;
foreach (string sValuein ArrKwdString)
{
Criteria1 +=string.Format("tblCompany.L_Keywords LIKE '%{0}%'", sValue);
Criteria2 +=string.Format("tblFranchise.L_Keywords LIKE '%{0}%'", sValue);
if ((iCount + 1) < ArrKwdString.Length)
Criteria1 +=" AND ";
Criteria2 +=" AND ";
iCount += 1;
CKWsearch = Criteria1;
SKWsearch = Criteria2;
TextBox1.Text = Criteria1;
TextBox2.Text = Criteria2;
}

}

|||

Please check out the article link I posted. There's risks/performance issues that you need to get an understanding of with dynamic SQL.

|||

I read the article but do not see what risk you are suggesting. If the partial WHERE string is generated within the C# code I do not see the injection risk unless there is a problem with the " " space delimiter used in the Split method for the incoming keyword string.

|||

The biggest risk is the SQL Injection attack. Performance issues include bad query plans, not storing query plans if you dont use sp_Executesql etc.

|||

I somewhat understand what you are talking about now (only after reading the article three times). I have abandoned the stored procedure and now am generating the Select statements in the code behind accessing them directly using SqlCommand object. I am hoping that will protect me from injection attacks as none of them are exposed to the users. Thank you for the expert advice. Sql is not a place for amateurs like myself to be mucking about. Your sage advice is greatly appreciated.

|||

Welcome. Glad to help.

Cant pass 0 in stored procedure parameter

Hi
I have an if clause in my code to add the final parameter value to send to the database.
If Page.User.IsInRole("MICMS") Then
cmdCheckUser.Parameters.Add("@.C_ID", 0)
Else
cmdCheckUser.Parameters.Add("@.C_ID", Session("C_ID"))
End If

If the user is in the role, the error is triggered saying that @.C_IDis expected by the stored procedure. If i then change the value from 0to 10, the stored procedure works fine.
Is there any reason that the stored procedure is failing when the value 0 is used and not when any other value is used?
Thanking you in advance.Because the parameters.add is overridden based on what is passed (look at them when you hit the left parens). Since you are passing a numerical value of a low number, it thinks that it is the sqldbtype. You will need to cast the value to a string cStr(YOURVALUEHERE).
Nick

Friday, February 24, 2012

can't modify stored proc which is in a publication

Hi

SQL 2005 sp1 - merge replication - HTTPS.

We have 2 publications for the database - one which has subscription.SyncType = SubscriptionSyncType.Automatic
and another with SyncType = SubscriptionSyncType.None.

The first publication is there so we can add new stored procs etc, the second contains the initial schema and the data.


When we try to modify a proc which is in the publication with SyncType = Automatic, the query never returns.

This is most urgent - thanks for your help.

Bruce

Do we have one or two subscriptions to publication one that contains the stored proc as a merge article in the publication?

|||

There are 2 subscriptions - one for each publication - but the proc is only in one publication

regards
Bruce

|||

1. Back to your original question - could the query (modifying the SP) be locked by another process so that it won't return?

2. Let us try to isolate this problem. If you can - colon the publication database, this publication (no second one), and subscribing database; does the same problem still occur?

Thanks.

|||

1. I doubt it..

2. 'colon the publication database' - what do you mean ?

thanks

|||

Create another publication database and create the same set of user tables/views/SPs. Just create one publication which includes the SP and other merge articles. See if you still can repro this issue with a single publication.

Thanks.

|||

We will try this tomorrow - but it's worth pointing out the following

a) the publication with SyncType = none -- has a few hundred stored procs - I can change any of these no worries

b) the publication with SyncType = automatic - initially just has 1 stored proc - so we can create the publication! - it's the procs we've added to this which we can't subsequently change.

Regards
Bruce

|||

Ok


I stripped it right back.

a. created a new database

b. added one proc

c. created the merge publication , snapshot etc

d. initalized ok

e. The query never returns....

Thanks
Bruce

|||

Can you share the proc prototype/definition (also I assume you use "ALTER PROCEDURE" to modify it)? I want to repro this case in house.

Thanks.

|||

Absolutely - it's a mindnumbing place-holder - it's just there so we can create the publication..

Don't laugh.

set ANSI_NULLS ON

set QUOTED_IDENTIFIER ON

GO

--

-- This is the proc for the 'extras' subscription

--

--

ALTER PROCEDURE [dbo].[aaaaPlaceHolder]

AS

BEGIN

SET NOCOUNT ON;

SELECT 'fish', 'cow', 'dog', 'elephant', 'pig', 'moo', 's', 't', 'dog', 'sheep'

END

|||

Bruce,

Thanks for your help. I have repro-ed this scenario on my machine. I need to work with my peers to diagnoise the real cause of it. Should get back to you once I have the answer.

Regards,

Leo

This posting is provided "AS IS" with no warranties, and confers no rights.

|||

As a temp solution - a dummy table can be created to join the SP in the same publication so that SP can be modified and replicated to the subscriber.

Leo

This posting is provided "AS IS" with no warranties, and confers no rights.

|||

Hi

I'll try it - has this been logged as a bug ? If so, how do I keep track of it ?

Thanks

|||

The bug was definitely filed and once I heard the decision/status I post it immediately.

Thanks

|||

This issue/bug should be addressed in Yukon Service Pack 2.

Leo

This posting is provided AS IS with no warranties, and confers no rights