Showing posts with label code. Show all posts
Showing posts with label code. Show all posts

Thursday, March 29, 2012

Help with converting code: VB code in SQL Server 2000->Visual Studio BI 2005

Hi all--I'm trying to convert a function which I inherited from a SQL Server 2000 DTS package to something usable in an SSIS package in SQL Server 2005. Given the original code here:

Function Main()

on error resume next

dim cn, i, rs, sSQL

Set cn = CreateObject("ADODB.Connection")

cn.Open "Provider=sqloledb;Server=<server_name>;Database=<db_name>;User ID=<sysadmin_user>;Password=<password>"

set rs = CreateObject("ADODB.Recordset")

set rs = DTSGlobalVariables("SQLstring").value

for i = 1 to rs.RecordCount

sSQL = rs.Fields(0).value

cn.Execute sSQL, , 128'adExecuteNoRecords option for faster execution

rs.MoveNext

Next

Main = DTSTaskExecResult_Success

End Function

This code was originally programmed in the SQL Server ActiveX Task type in a DTS package designed to take an open-ended number of SQL statements generated by another task as input, then execute each SQL statement sequentially. Upon this code's success, move on to the next step. (Of course, there was no additional documentation with this code. :-)

Based on other postings, I attempted to push this code into a Visual Studio BI 2005 Script Task with the following change:

public Sub Main()

...

Dts.TaskResult = Dts.Results.Success

End Class

I get the following error when I attempt to compile this:

Error 30209: Option Strict On requires all variable declarations to have an 'As' clause.

I am new to Visual Basic, so I'm on a learning curve here. From what I know of this script:
- The variables here violate the new Option Strict On requirement in VS 2005 to declare what type of object your variable is supposed to use.

- I need to explicitly declare each object, unless I turn off the Option Strict On (which didn't seem recommended, based on what I read).

Given this statement:

dim cn, i, rs, sSQL

I'm looking at "i" as type Integer; rs and sSQL are open-ended arrays, but can't quite figure out how to read the code here:

Set cn = CreateObject("ADODB.Connection")

cn.Open "Provider=sqloledb;Server=<server_name>;Database=<db_name>;User ID=<sysadmin_user>;Password=<password>"

set rs = CreateObject("ADODB.Recordset")

This code seems to create an instance of a COM component, then pass provider information and create the recordset being passed in by the previous task, but am not sure whether this syntax is correct for VS 2005 or what data type declaration to make here. Any ideas/help on how to rewrite this code would be greatly appreciated!

Option Strict controls what we call "late binding." If option strict is ON, then what happens is that the compiler will generate code that takes full advantage of the type system in the CLR. This means that each variable has a compile-time type (hence you need to specify the "As" clause), and because each variable has a compile-time type, the IL that the compiler generates is fast (for example, method calls are translated to a "call" or a "callvirt" IL instruction).

If you turn option strict OFF, this is what is known as the "late binding" mode. There is no equivalent in C#. What the late binding mode allows you to do is to leave variables specified as "object" (and if you omit the "As" clause, the type is assumed to be "object"). The compiler, because it does not know what the type is, needs to generate code that calls the Visual Basic Runtime helpers to execute method calls.

Because of this, the compiler cannot provide checks for you during compile time. For example, you can do something like this:

dim o = CreateObject("ADODB.Connection")
o.foo()

The compiler will not check whether the "foo" method exists, because it doesn't know the type of o. And if "foo" indeed does not exist, you will get a runtime exception. Runtime exceptions are much harder to debug and diagnose; this is probably why people advise against turning option strict off.

However, in certain scenarios, such as yours, I believe that turning option strict off will make life easier. The compiler may not be as helpful, but it will make your code easier to understand.

The CreateObject calls are indeed creating COM objects. Your analysis of what the code is doing is correct. The .NET equivalent of the ADODB.Connection and ADODB.Recordset classes live in the "System.Data" namespace. Take a look here for some information: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemData.asp

I hope this helps - feel free to post any more questions or issues that you run into here :)|||

Hi Timothy--Thanks for the analysis, and the suggestion of turning this option off. How do I do that for just this package? I read somewhere (don't remember the URL at the moment) that I had to turn this option off through a configuration parameter in a file ending in .vbproj. However, the ultimate goal is store this package in the SQL Server database and so give it the ability to schedule it through the SQL Server Agent. That doesn't seem feasible if I have to store connection information externally, which is a security risk...and I can't find any files with that name anyway.

I tried to add the following into the function:

Option Strict Off

That caused another compilation error, unless I'm missing something else. Any ideas on how to turn the Option Strict off for just this task?

|||

Better to leave Option Strict On.

Dim i as Integer

Dim cn as ADODB.Connection

Dim rs as ADODB.Recordset

These declarations will require a reference in the Script task project to the ADODB primary interop assembly.

-Doug

|||What was the error you get with Option Strict Off?

The finest level of granularity is to turn option strict off at the file level - put this at the top of the file:
Option Strict Off

If you pursue any solution where you need to turn on/off option strict, it's best to at the very least put the code you want option strict off for in another file.

I agree too that Option Strict should typically be left On, but there are situations where turning it Off can make it easier to code, at the expenses that I mentioned above.|||

Thanks all--These prior posts helped me work around the problem. It's appreciated--problem solved!

- Jonathan

Help with converting code: VB code in SQL Server 2000->Visual Studio BI 2005

Hi all--I'm trying to convert a function which I inherited from a SQL Server 2000 DTS package to something usable in an SSIS package in SQL Server 2005. Given the original code here:

Function Main()

on error resume next

dim cn, i, rs, sSQL

Set cn = CreateObject("ADODB.Connection")

cn.Open "Provider=sqloledb;Server=<server_name>;Database=<db_name>;User ID=<sysadmin_user>;Password=<password>"

set rs = CreateObject("ADODB.Recordset")

set rs = DTSGlobalVariables("SQLstring").value

for i = 1 to rs.RecordCount

sSQL = rs.Fields(0).value

cn.Execute sSQL, , 128'adExecuteNoRecords option for faster execution

rs.MoveNext

Next

Main = DTSTaskExecResult_Success

End Function

This code was originally programmed in the SQL Server ActiveX Task type in a DTS package designed to take an open-ended number of SQL statements generated by another task as input, then execute each SQL statement sequentially. Upon this code's success, move on to the next step. (Of course, there was no additional documentation with this code. :-)

Based on other postings, I attempted to push this code into a Visual Studio BI 2005 Script Task with the following change:

public Sub Main()

...

Dts.TaskResult = Dts.Results.Success

End Class

I get the following error when I attempt to compile this:

Error 30209: Option Strict On requires all variable declarations to have an 'As' clause.

I am new to Visual Basic, so I'm on a learning curve here. From what I know of this script:
- The variables here violate the new Option Strict On requirement in VS 2005 to declare what type of object your variable is supposed to use.

- I need to explicitly declare each object, unless I turn off the Option Strict On (which didn't seem recommended, based on what I read).

Given this statement:

dim cn, i, rs, sSQL

I'm looking at "i" as type Integer; rs and sSQL are open-ended arrays, but can't quite figure out how to read the code here:

Set cn = CreateObject("ADODB.Connection")

cn.Open "Provider=sqloledb;Server=<server_name>;Database=<db_name>;User ID=<sysadmin_user>;Password=<password>"

set rs = CreateObject("ADODB.Recordset")

This code seems to create an instance of a COM component, then pass provider information and create the recordset being passed in by the previous task, but am not sure whether this syntax is correct for VS 2005 or what data type declaration to make here. Any ideas/help on how to rewrite this code would be greatly appreciated!

Option Strict controls what we call "late binding." If option strict is ON, then what happens is that the compiler will generate code that takes full advantage of the type system in the CLR. This means that each variable has a compile-time type (hence you need to specify the "As" clause), and because each variable has a compile-time type, the IL that the compiler generates is fast (for example, method calls are translated to a "call" or a "callvirt" IL instruction).

If you turn option strict OFF, this is what is known as the "late binding" mode. There is no equivalent in C#. What the late binding mode allows you to do is to leave variables specified as "object" (and if you omit the "As" clause, the type is assumed to be "object"). The compiler, because it does not know what the type is, needs to generate code that calls the Visual Basic Runtime helpers to execute method calls.

Because of this, the compiler cannot provide checks for you during compile time. For example, you can do something like this:

dim o = CreateObject("ADODB.Connection")
o.foo()

The compiler will not check whether the "foo" method exists, because it doesn't know the type of o. And if "foo" indeed does not exist, you will get a runtime exception. Runtime exceptions are much harder to debug and diagnose; this is probably why people advise against turning option strict off.

However, in certain scenarios, such as yours, I believe that turning option strict off will make life easier. The compiler may not be as helpful, but it will make your code easier to understand.

The CreateObject calls are indeed creating COM objects. Your analysis of what the code is doing is correct. The .NET equivalent of the ADODB.Connection and ADODB.Recordset classes live in the "System.Data" namespace. Take a look here for some information: http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfSystemData.asp

I hope this helps - feel free to post any more questions or issues that you run into here :)|||

Hi Timothy--Thanks for the analysis, and the suggestion of turning this option off. How do I do that for just this package? I read somewhere (don't remember the URL at the moment) that I had to turn this option off through a configuration parameter in a file ending in .vbproj. However, the ultimate goal is store this package in the SQL Server database and so give it the ability to schedule it through the SQL Server Agent. That doesn't seem feasible if I have to store connection information externally, which is a security risk...and I can't find any files with that name anyway.

I tried to add the following into the function:

Option Strict Off

That caused another compilation error, unless I'm missing something else. Any ideas on how to turn the Option Strict off for just this task?

|||

Better to leave Option Strict On.

Dim i as Integer

Dim cn as ADODB.Connection

Dim rs as ADODB.Recordset

These declarations will require a reference in the Script task project to the ADODB primary interop assembly.

-Doug

|||What was the error you get with Option Strict Off?

The finest level of granularity is to turn option strict off at the file level - put this at the top of the file:
Option Strict Off

If you pursue any solution where you need to turn on/off option strict, it's best to at the very least put the code you want option strict off for in another file.

I agree too that Option Strict should typically be left On, but there are situations where turning it Off can make it easier to code, at the expenses that I mentioned above.|||

Thanks all--These prior posts helped me work around the problem. It's appreciated--problem solved!

- Jonathan

Tuesday, March 27, 2012

Help with column Insert

Hi,

I have some values I want put into a table, but the values are from other sources and I dont know how to retrieve them..

I'll show my code, and the bold is explaining what I want inserted and where from. I'd apprechiate if someone could help me with syntax etc. There are 2 about getting value from another table and one about just putting in straight forward text..:

command.CommandText = "INSERT INTO Messages (sendername,recievername,message,Date,subject) VALUES (@.sendername,@.recievername,@.message,@.date,@.subject)";


command.Parameters.Add("@.sendername", System.Web.HttpContext.Current.User.Identity.Name)

command.Parameters.Add("@.recievername",every value of column named Usersname of the Transactions table, WHERE Itemid=Itemid in the gridview on this page);


command.Parameters.Add("@.message",the value of items table - column 'paymentinstructions' WHERE Username=System.Web.HttpContext.Current.User.Identity.Name);


command.Parameters.Add("@.subject",some text: IMPORTANT - Payment Required);


command.Parameters.Add("@.date", DateTime.Now.ToString());


command.ExecuteNonQuery();

Thanks alot if anyone can help me with those three things..

Jon

If 10 people are to receive the message, are there 10 message records or one?

If one, how are the 10 usernames supposed to be formatted? comma-separated values, separated by semi-colons?

|||

I was hoping to have 1 record, with a large list of usernames. I assume it will work if they are seperated by anything, but with a space - peoples messages are called up if the recievername column has their username in it. Will it work if it also has other writing (i.e. other peoples usernames)?

Thanks

Jon

|||

jbear123:

command.Parameters.Add("@.recievername",every value of column named Usersname of the Transactions table, WHERE Itemid=Itemid in the gridview on this page);


command.Parameters.Add("@.message",the value of items table - column 'paymentinstructions' WHERE Username=System.Web.HttpContext.Current.User.Identity.Name);


command.Parameters.Add("@.subject",some text: IMPORTANT - Payment Required);

I just took the time toreally pay attention to what you are doing in business terms instead of just the coding issues.

This is a collection's application? If you sent out a message with my name on it, telling hundreds of other people I hadn't paid up, I would be really angry.

Angry enough to tell you impolite things and never do business with you again.

Depending upon what country you live in or are sending the messages to, it might even be illegal. Particularly if you made a mistake and they did not owe you anything - that would be libel under US law.

That said, I have one other question. The payment instructions are tied to the user who is logged into the page, not the user receiving the message? That was a bit surprising. Or are they tied to the user receiving the message?

As for filling in the values, you just need a few strings to store them in.

Issue a query to get the list of usernames and loop thru them. Use the StringBuilder to concatenate them.

Issue another query to get the payment instructions.

|||

david wendelken:

As for filling in the values, you just need a few strings to store them in.

Issue a query to get the list of usernames and loop thru them. Use the StringBuilder to concatenate them.

Issue another query to get the payment instructions.

This is what I was after. Would you mind explaining this a bit more throughly for someone of a lower coding ability..? i.e. how do I issue the query to get the list of usernames? Compared to the code I posted, how would it be structured? Concatenate them?

Re: Legal issues - Thank you for your concern, but you shouldn't worry about it.

Thanks for your help!

Jon

|||

david wendelken:

As for filling in the values, you just need a few strings to store them in.

Issue a query to get the list of usernames and loop thru them. Use the StringBuilder to concatenate them.

Issue another query to get the payment instructions.

This is what I was after. Would you mind explaining this a bit more throughly for someone of a lower coding ability..? i.e. how do I issue the query to get the list of usernames? Compared to the code I posted, how would it be structured? Concatenate them?

Re: Legal issues - Thank you for your concern, but you shouldn't worry about it.

Thanks for your help!

Jon

|||

You already know how to issue a sql command via the SqlCommand object. Instead of an update command, you need to issue a query:

My guess as to your query would be "select distinct usersname from transactions where itemid = @.itemid"

You will have to pass in the itemid as a parameter, and issue an ExecuteQuery instead of an ExecuteNonQuery. You will be putting the results of the query into a DataReader and looping thru it. Just google or look it up any pretty much any asp book. This is basic, beginner level stuff and it's well documented all over the place - so I'm not going to do it again. :)

Inside the DataReader loop, you can concatenate the usernames you return into a string. It's best to use the StringBuilder class when you are looping. Again, google or look up StringBuilder in the manual.

I think you would be better served slogging thru this step yourself rather than having someone hand it to you. You'll learn it better, and this is bread-and-butter code that you'll use all the time, so it needs to be second nature. I'll keep an eye out on this thread in case you get stuck someplace.


|||

Hi,

I think I have the idea - could you confirm this for me:

I keep the insert commands, but before them I create a command to select all the info that I want inserted (from different tables etc), then using the insert command reference the results of the select command info?

If thats not what yopu meant, would that work anyway?

Thanks,

Jon

|||

I hope it will work as I have done it now..I created datalists showing the data I want to be inserted.

The only thing I cant do is link the results of the datalist (where i selected the data I want(visible=false)) etc to the add parameter section.

E.g:

command.Parameters.AddWithValue("@.sendername", System.Web.HttpContext.Current.User.Identity.Name);
command.Parameters.Add("@.recievername",how do I link to results of the datalist here? I'd have to have a comma in between each result);
command.Parameters.AddWithValue("@.message", TextBox2.Text);
command.Parameters.AddWithValue("@.subject", TextBox3.Text);
command.Parameters.AddWithValue("@.date", DateTime.Now.ToString());

Please could you briefly explain, as soon as I know that I can apply it to problemsall over the page and my site will be done!

Thanks alot

Jon

|||

Before you get to this point, create a string to hold the receivername values.

Loop thru the datalist, and for each entry in the datalist, append the next receiver.

|||

I'll give it a go. Just briefly before I leave you alone for a while (sorry!)-

If I create a string, how do I do that for many values (i.e. many usernames),

By loop thru, you mean just use find the string on the datalist?

And what do you mean by append the next receiver? use: + 'next receiver'?

Cheers,

Jon

|||

Hi,

I have:

SqlCommand command = new SqlCommand();
command.Connection = con;

command.CommandText = "INSERT INTO Messages (sendername,recievername,message,Date,subject) VALUES (@.sendername,@.recievername,@.message,@.date,@.subject)";
command.Parameters.AddWithValue("@.sendername", System.Web.HttpContext.Current.User.Identity.Name);
DataView dv = SqlDataSource2.Select(DataSourceSelectArguments.Empty) as DataView;
string receivername = dv[0]["receivername"].ToString();
command.Parameters.AddWithValue("@.recievername", receivername);
command.Parameters.AddWithValue("@.message", TextBox2.Text);
command.Parameters.AddWithValue("@.subject", TextBox3.Text);
command.Parameters.AddWithValue("@.date", DateTime.Now.ToString());
command.ExecuteNonQuery();

con.Close();
command.Dispose();
return true;

so far. How can I make values seperate by commas?

Thanks,

Jon

sql

Help with code

I have this code in a DTS package which is:

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

drop proc VerifyRequest
go
/*
* VerifyRequestTransfer - run a command that looks for @.filename in the output
*

*
* This proc looks for a file matching 'tbl_%' in the output of an ftp command.
* The output message reports success/failure of transfer.
* A return code of 1 indicates success
* Return code = 0 indicates failure.
*
* How it Works:
* ftp is executed using @.ftpcommandfile as input to the -s parameter.
* The output of ftp is written to a table
* The table is cleared of garbage records
* The count of records matching @.filename is checked
* if the count = 1 then there success!
*/
CREATE proc VerifyRequest
@.filename varchar(200),
@.ftpcommandfile varchar(1000)
as

declare @.rc int
declare @.rows int, @.errcode int, @.rows2 int
set @.rc = 0
set @.rows = -9998

set nocount on
-- build a table containing list of files in Request directory
if exists (select * from tempdb.dbo.sysobjects where name='RequestFiles' and type = 'U')
drop table tempdb.dbo.RequestFiles
create table tempdb.dbo.RequestFiles (
line_no int identity(1,1) Primary key clustered,
Filename varchar(200) NULL
)
declare @.cmd varchar(2000)

--Get list of remote files
set @.cmd = 'ftp -i -s:' + @.ftpcommandfile
Insert into tempdb.dbo.RequestFiles (Filename)
Exec master.dbo.xp_cmdshell @.cmd
select @.rows = @.@.rowcount, @.errcode = @.@.error
if @.rows = 0 OR @.errcode != 0
begin
set @.rc = -1
goto done
end

-- remove non-files and already processed files ( there might have been old files on remotesystem )
Delete
From tempdb.dbo.RequestFiles
Where coalesce(Filename, '') not like '%tbl_%'
-- check count
select @.rows = (select count(*) from tempdb.dbo.RequestFiles
Where tempdb.dbo.RequestFiles.Filename like '%'+@.filename+'%' )

if @.rows = 1
set @.rc = 1
done:
return @.rc
go

Now the message I am getting is:

The task reported failure on execution. Procedure 'VerifyRequest' expects Parameter '@.filename', which was not supplied.

I don't know where to set this parameter.

I hope someone can help.

Thanks

LystraYou will need to supply both the @.filename and @.ftpcommandfile parameters when you call the procedure from your code:

VerifyRequest 'C:\Yourfile.nam', 'C:\YourCommandFile.nam'|||If that was THAT easy the error would have referenced @.ftpcommandfile parameter, not @.filename.|||THe vb scripts that is first started which is:

Function Main()
DTSGlobalVariables("PostDate") = month(now()) & "/" & day(now()) & "/" & year(now())
dim tmp
dim filename

tmp = right("0" & datepart("m", DTSGlobalVariables("PostDate")), 2)
tmp = tmp & right("0" & datepart("d", DTSGlobalVariables("PostDate")), 2)
tmp = tmp & datepart("yyyy", DTSGlobalVariables("PostDate"))
DTSGlobalVariables("Datestamp") = tmp
filename = DTSGlobalVariables("TransferFileNameRoot") & DTSGlobalVariables("Datestamp") & DTSGlobalVariables("FileExtension")
DTSGlobalVariables("TransferFilename") = DTSGlobalVariables("TransferFileDir") & "\" & DTSGlobalVariables("TransferFileNameRoot") & DTSGlobalVariables("Datestamp") & DTSGlobalVariables("FileExtension")

' use the output file name to generate an FTP command file
set oFSO = CreateObject("Scripting.FileSystemObject")
set oFile = oFSO.OpenTextFile( DTSGlobalVariables ("TransferFTPCommands").Value , 2, 1)
oFile.writeline ("open " & DTSGlobalVariables("TransferFTPServer"))
oFile.writeline DTSGlobalVariables("TransferFTPLogin")
oFile.writeline DTSGlobalVariables("TransferFTPPassword")
oFile.writeline "cd /fs11/infiles"
oFile.writeline "mput " & DTSGlobalVariables("TransferFilename").Value
oFile.writeline "quit"
oFile.Close
set oFile = nothing

' Generate an FTP command file to verify that transfer worked.
set oFile = oFSO.OpenTextFile( DTSGlobalVariables ("TransferFTPVerifyReq").Value , 2, 1)
oFile.writeline ("open " & DTSGlobalVariables("TransferFTPServer"))
oFile.writeline DTSGlobalVariables("TransferFTPLogin")
oFile.writeline DTSGlobalVariables("TransferFTPPassword")
oFile.writeline "cd /fs11/infiles" & vbCRLF & "ls -l " & vbCRLF & "quit"
oFile.Close
set oFile = nothing
set oFSO = nothing

' save the output filename into the transfer verification query
tmp = "Select count(*) from tempdb.dbo.RequestFiles " & vbCRLF & _
"Where tempdb.dbo.RequestFiles.Filename like '%"+ filename + "%'"
'Create a new query to look for files with the output filename
' find the task that counts the number of transferred files
set oTasks = DTSGlobalVariables.Parent.Tasks
for each task in oTasks
if task.Properties("Description") = "Evaluate File Count" then
' set the Query in DynamicProperties Task so that it checks for today's file
For Each oAssignment In task.CustomTask.Assignments
if instr( oAssignment.DestinationPropertyID , "'TransferredFileCount'" ) then
oAssignment.SourceQuerySQL = tmp
end if
next
end if
next
Main = DTSTaskExecResult_Success
End Function

Since I have created a ftp transfer file that lists the file names and should put the files in a temp table. I am having trouble with the ftp command to list the file in my file.

Thanking you in advance.

Lystra

Help with case when

I need help.
This is the code I currently have and need to change:
p.code as "Code",
p.detail_type as "Detail Type",

p.code shows diagnostic code numbers and billing procedure numbers
while p.detail_type indicate which is which. Diagnostic code numbers
are designated as '-2' (minus 2) in the 'detail_type' and procedure
codes are designated as '-4' (minus 4) in the 'detail_type.' The query
I am using now (see below) gives me duplicate appt dates to show both
the diagnostic code and procedure code. I need to clean this up a bit.

What I want this to do is find a statement that will separate the codes
into diagnosis numbers and procedure numbers and place these numbers in
different columns in the ad hoc report that is generated.

I would like something to the effect of:
If p.detail_type = -2 then place the code number in a column known as
"Code"
If p.detail_type - -4 then place the code number in a column known as
"Procedure"

Any ideas on how to write this?

Select
/* Individual Client Task List */

a.Provider as "Provider",
a.Apptdate as "Session Date",
a.Appttype as "Session Type",
p.code as "Code",
p.detail_type as "Detail Type",
a.Complaint1 as "Note Written",
a.Signoffinits as "Co-Signed",
a.Lastname as "Lastname",
a.Firstname as "Firstname"

Quote:

Originally Posted by

>From Appointments a, Patientmedicalrecords p


Where a.uniquenumber = p.appt_uniquenumber
and a.Division = 3
and a.Inactive = 0
and a.Personal = 0
and a.Ingroup = 0
and a.Appttype not like 'TELE'
and a.Apptdate between '1-Jul-2006' and sysdate - 1
and a.Appttype not in ('AEP2','AEP4','AOD','TOCE2','TOCE4','ETOH2
Class','AEP4 Class','AOD1 Class')
and (substr(a.Complaint1,1,2) = 'TS'
or a.Complaint1 like 'Secretary Signed'
or a.Complaint1 is null
or a.Signoffinits is null)
and a.Patientnumber not in ('57629','82362','125163','139842')
Order by
a.Provider,
a.Apptdate

Thanks for your help. dwerden.dwerden (dwerden@.purdue.edu) writes:

Quote:

Originally Posted by

I need help.
This is the code I currently have and need to change:
p.code as "Code",
p.detail_type as "Detail Type",
>
p.code shows diagnostic code numbers and billing procedure numbers
while p.detail_type indicate which is which. Diagnostic code numbers
are designated as '-2' (minus 2) in the 'detail_type' and procedure
codes are designated as '-4' (minus 4) in the 'detail_type.' The query
I am using now (see below) gives me duplicate appt dates to show both
the diagnostic code and procedure code. I need to clean this up a bit.
>
>
What I want this to do is find a statement that will separate the codes
into diagnosis numbers and procedure numbers and place these numbers in
different columns in the ad hoc report that is generated.
>
I would like something to the effect of:
If p.detail_type = -2 then place the code number in a column known as
"Code"
If p.detail_type - -4 then place the code number in a column known as
"Procedure"
>
Any ideas on how to write this?


CASE p.detail_type WHEN -2 THEN p.code END AS Code,
CASE p.detail_type WHEN -4 THEN p.code END AS Procedure,

--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx|||Thanks, Erland. Your code separated them like I wanted but I continue
to get 2 entries for each actual appointment (as shown below).

Provider--Session Date--Session Type--Code--Proceure--Note
Written--Co-Signed
Bossick--7/6/2006--1 hr Session--309.28--(empty)--Done--bb
Bossick--7/6/2006--1 hr Session--(empty)--99212--Done--bb

Is there a way to force these to combine into only one entry like this?

Provider--Session Date--Session Type--Code--Procedure--Note
Written--Co-Signed
Bossick--7/6/2006--1 hr Session--309.28--99212--Done--bb

Erland Sommarskog wrote:

Quote:

Originally Posted by

CASE p.detail_type WHEN -2 THEN p.code END AS Code,
CASE p.detail_type WHEN -4 THEN p.code END AS Procedure,
--
Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
>
Books Online for SQL Server 2005 at
http://www.microsoft.com/technet/pr...oads/books.mspx
Books Online for SQL Server 2000 at
http://www.microsoft.com/sql/prodin...ions/books.mspx


Select
/* Individual Client Task List */

a.Provider as "Provider",
a.Apptdate as "Session Date",
a.Appttype as "Session Type",
CASE p.detail_type WHEN -2 THEN p.code END AS Code,
CASE p.detail_type WHEN -4 THEN p.code END AS Procedure,
a.Complaint1 as "Note Written",
a.Signoffinits as "Co-Signed",
a.Lastname as "Lastname",
a.Firstname as "Firstname"

Quote:

Originally Posted by

>From Appointments a, Patientmedicalrecords p


Where a.uniquenumber = p.appt_uniquenumber
and a.Division = 3
and a.Inactive = 0
and a.Personal = 0
and a.Ingroup = 0
and a.Appttype not like 'TELE'
and a.Apptdate between '1-Jul-2006' and sysdate - 1
and a.Appttype not in ('AEP2','AEP4','AOD','TOCE2','TOCE4','ETOH2
Class','AEP4 Class','AOD1 Class')
and (substr(a.Complaint1,1,2) = 'TS'
or a.Complaint1 like 'Secretary Signed'
or a.Complaint1 is null
or a.Signoffinits is null)
/* Next line excludes Pyle, Kyler, Aunt Bee, Rowdy */
and a.Patientnumber not in ('57629','82362','125163','139842')
Order by
a.Provider,
a.Apptdate,
a.Lastname|||Assuming there is at most one row in Patientmedicalrecords with detail_type
= -2 and at most one with detail_type = -4 for each matching row in
Appointments, then
Change:
CASE p.detail_type WHEN -2 THEN p.code END AS Code,
CASE p.detail_type WHEN -4 THEN p.code END AS Procedure,

To:
Coalesce(p1.Code,'') As Code,
Coalesce(p2.Code,'') As Procedure,

And change:
From Appointments a, Patientmedicalrecords p
Where a.uniquenumber = p.appt_uniquenumber
and a.Division = 3
and a.Inactive = 0
<rest of where conditions>

to:

From Appointments a
Left Outer Join Patientmedicalrecords p1 On a.uniquenumber =
p1.appt_uniquenumber
And p1.detail_type = -2
Left Outer Join Patientmedicalrecords p1 On a.uniquenumber =
p12.appt_uniquenumber
And p1.detail_type = -4
Where a.Division = 3
and a.Inactive = 0
<rest of where conditions>

Tom

"dwerden" <dwerden@.purdue.eduwrote in message
news:1154457844.644843.182100@.m73g2000cwd.googlegr oups.com...

Quote:

Originally Posted by

Thanks, Erland. Your code separated them like I wanted but I continue
to get 2 entries for each actual appointment (as shown below).
>
Provider--Session Date--Session Type--Code--Proceure--Note
Written--Co-Signed
Bossick--7/6/2006--1 hr Session--309.28--(empty)--Done--bb
Bossick--7/6/2006--1 hr Session--(empty)--99212--Done--bb
>
Is there a way to force these to combine into only one entry like this?
>
Provider--Session Date--Session Type--Code--Procedure--Note
Written--Co-Signed
Bossick--7/6/2006--1 hr Session--309.28--99212--Done--bb
>
>
Erland Sommarskog wrote:

Quote:

Originally Posted by

> CASE p.detail_type WHEN -2 THEN p.code END AS Code,
> CASE p.detail_type WHEN -4 THEN p.code END AS Procedure,
>--
>Erland Sommarskog, SQL Server MVP, esquel@.sommarskog.se
>>
>Books Online for SQL Server 2005 at
>http://www.microsoft.com/technet/pr...oads/books.mspx
>Books Online for SQL Server 2000 at
>http://www.microsoft.com/sql/prodin...ions/books.mspx


>
Select
/* Individual Client Task List */
>
a.Provider as "Provider",
a.Apptdate as "Session Date",
a.Appttype as "Session Type",
CASE p.detail_type WHEN -2 THEN p.code END AS Code,
CASE p.detail_type WHEN -4 THEN p.code END AS Procedure,
a.Complaint1 as "Note Written",
a.Signoffinits as "Co-Signed",
a.Lastname as "Lastname",
a.Firstname as "Firstname"

Quote:

Originally Posted by

>>From Appointments a, Patientmedicalrecords p


Where a.uniquenumber = p.appt_uniquenumber
and a.Division = 3
and a.Inactive = 0
and a.Personal = 0
and a.Ingroup = 0
and a.Appttype not like 'TELE'
and a.Apptdate between '1-Jul-2006' and sysdate - 1
and a.Appttype not in ('AEP2','AEP4','AOD','TOCE2','TOCE4','ETOH2
Class','AEP4 Class','AOD1 Class')
and (substr(a.Complaint1,1,2) = 'TS'
or a.Complaint1 like 'Secretary Signed'
or a.Complaint1 is null
or a.Signoffinits is null)
/* Next line excludes Pyle, Kyler, Aunt Bee, Rowdy */
and a.Patientnumber not in ('57629','82362','125163','139842')
Order by
a.Provider,
a.Apptdate,
a.Lastname
>

|||>p.code shows diagnostic code numbers and billing procedure numbers while p.detail_type indicate which is which. <<

Stop writing code like this. You never cram two or more attributes
into one column. Hey, why not have a column for "squids and
automobiles", too?

What you have done is re-invent the variant record from COBOL, FORTRAN,
Pascal, etc. and other procedural languages.|||That's a great idea!

I think I remember seeing a squid looking automobile thingy in some animated
film recently.

Joe, Did you create the database used by the film company?

--
Arnie Rowland, Ph.D.
Westwood Consulting, Inc

Most good judgment comes from experience.
Most experience comes from bad judgment.
- Anonymous

"--CELKO--" <jcelko212@.earthlink.netwrote in message
news:1154462822.641976.57700@.m73g2000cwd.googlegro ups.com...

Quote:

Originally Posted by

Quote:

Originally Posted by

Quote:

Originally Posted by

>>p.code shows diagnostic code numbers and billing procedure numbers while
>>p.detail_type indicate which is which. <<


>
Stop writing code like this. You never cram two or more attributes
into one column. Hey, why not have a column for "squids and
automobiles", too?
>
What you have done is re-invent the variant record from COBOL, FORTRAN,
Pascal, etc. and other procedural languages.
>

Help with CASE T-SQL

Anyone have much experience with SQL Server T-SQL CASE statement?
I have some code that someone else wrote that looks like this:
SELECT m.messageID, m.isTop,
CASE @.Mode
WHEN 10 THEN m.subject
WHEN 12 THEN p.userID
END
FROM Messages m
INNER JOIN People p ON m.userID=p.userID
WHERE [blah][blah][blah].
What I need to do is return something that is not the userID, but still have
that name. This did not work:
SELECT m.messageID, m.isTop,
CASE @.Mode
WHEN 10 THEN m.subject
WHEN 12 THEN pr.userName As userID
END
FROM Messages m
INNER JOIN People p ON m.userID=p.userID
INNER JOIN Personalize pr ON m.userID=pr.userID
WHERE [blah][blah][blah].
SQL dies on the "As"... (or, if I leave out the "As", it dies on "userID")
Any idea how I can do this?
Thanks,
OwenCASE @.Mode
WHEN 10 THEN m.subject
WHEN 12 THEN pr.userName
END As UserID
"Owen Mortensen" <ojm.NO_SPAM@.acm.org> wrote in message
news:OWsmKlxPGHA.3460@.TK2MSFTNGP15.phx.gbl...
> Anyone have much experience with SQL Server T-SQL CASE statement?
> I have some code that someone else wrote that looks like this:
> SELECT m.messageID, m.isTop,
> CASE @.Mode
> WHEN 10 THEN m.subject
> WHEN 12 THEN p.userID
> END
> FROM Messages m
> INNER JOIN People p ON m.userID=p.userID
> WHERE [blah][blah][blah].
> What I need to do is return something that is not the userID, but still
> have that name. This did not work:
> SELECT m.messageID, m.isTop,
> CASE @.Mode
> WHEN 10 THEN m.subject
> WHEN 12 THEN pr.userName As userID
> END
> FROM Messages m
> INNER JOIN People p ON m.userID=p.userID
> INNER JOIN Personalize pr ON m.userID=pr.userID
> WHERE [blah][blah][blah].
> SQL dies on the "As"... (or, if I leave out the "As", it dies on "userID")
> Any idea how I can do this?
> Thanks,
> Owen
>|||Thanks. This variation on that theme actually worked:
CASE @.Mode WHEN 10 THEN m.subject END As subject,
CASE @.Mode WHEN 12 THEN pr.userName END As UserID
"Norman Yuan" <NotReal@.NotReal.not> wrote in message
news:utqlB9xPGHA.1216@.TK2MSFTNGP14.phx.gbl...
> CASE @.Mode
> WHEN 10 THEN m.subject
> WHEN 12 THEN pr.userName
> END As UserID
>
> "Owen Mortensen" <ojm.NO_SPAM@.acm.org> wrote in message
> news:OWsmKlxPGHA.3460@.TK2MSFTNGP15.phx.gbl...
>

Help with Case Statement

I have the following code in which I need to check something in the ELSE. The problem is how to form it correctly. I could use a cursor I guess to transverse through the records.

In the Else, I want to:

1) Check the count of the results of my statement. IF > 1 then check to see if m.original is between lowlimit and highlimit for any of those records found
2) If m.original is between the lowlimit and highlimit, then select Fee1 from FeeScheduleDetails

m.original and m.FeeSchedule is out here somewhere, just know this...it's part of the query that you don't see

CASE WHEN Len(c.FeeSchedule) < 3 then
CONVERT(int, c.feeSchedule)
ELSE
Select Count(*) FROM FeeScheduleDetails fd
INNER JOIN Master m ON m.FeeSchedule = fd.code

IF Count(*) > 3
Check to see if m.original is BETWEEN fd.lowlimit AND fd.highlimit
If yes, then bring me back fee1, if no then just bring me back m.FeeSchedule
END AS FeeSchedule

Master

FeeSchedule

FeeScheduleDetails
-
Code
LowLimit
HighLimit
Fee1

? Hi dba123, In your qeury pseudo-code, where is the alias c (used in c.FeeSchedule) defined? It's easier to help you if you post CREATE TABLE statements for your table structures, INSERT statements with some rows of sample data and the expected results of the query. Not only will that help others understand what you ask, it also enables them to easily test what they post. -- Hugo Kornelis, SQL Server MVP <dba123@.discussions.microsoft.com> schreef in bericht news:7fb6e0f7-ae20-451c-abee-677d4d3ee6f8@.discussions.microsoft.com... I have the following code in which I need to check something in the ELSE. The problem is how to form it correctly. I could use a cursor I guess to transverse through the records.In the Else, I want to:1) Check the count of the results of my statement. IF > 1 then check to see if m.original is between lowlimit and highlimit for any of those records found2) If m.original is between the lowlimit and highlimit, then select Fee1 from FeeScheduleDetailsm.original and m.FeeSchedule is out here somewhere, just know this...it's part of the query that you don't seeCASE WHEN Len(c.FeeSchedule) < 3 thenCONVERT(int, c.feeSchedule)ELSESelect Count(*) FROM FeeScheduleDetails fdINNER JOIN Master m ON m.FeeSchedule = fd.codeIF Count(*) > 3Check to see if m.original is BETWEEN fd.lowlimit AND fd.highlimitIf yes, then bring me back fee1, if no then just bring me back m.FeeScheduleEND AS FeeScheduleMasterFeeScheduleFeeScheduleDetails-CodeLowLimitHighLimitFee1|||

thanks for the heads up. Here's the entire query...and a new attept at fee1

INSERT INTO ReportingServer.dbo.DCR

SELECT

m.customer,

c.name,

c.customer,

c.state,

CASE WHEN Len(c.FeeSchedule) < 3 THEN

CONVERT(int, c.feeSchedule)

WHEN Len(c.FeeSchedule) > 3 THEN

SELECT fd.Fee1 FROM FeeScheduleDetails fd

where c.feeSchedule = fd.code AND m.original BETWEEN fd.LowLimit AND fd.HighLimit

ELSE

CONVERT(int, c.feeSchedule)

END AS FeeSchedule,

m.Branch,

CASE WHEN ph.batchtype = 'PUR' OR ph.batchtype = 'PAR' OR ph.batchtype = 'PCR' Then

(ph.totalpaid - ph.ForwardeeFee)

ELSE

0.00

END AS [Posted Amount],

ph.systemmonth,

ph.datepaid,

ph.totalpaid,

ph.batchtype,

m.desk,

0 AS [New Old CC],

0 AS [New Old PDC],

'In-House' AS Type,

1 AS Active,

ph.UID,

m.number,

dc.amount CC,

p.amount AS PDC,

m.original,

CONVERT(money, ph.OverPaidAmt),

0,

0,

''

FROM dbo.Master m (NOLOCK) LEFT JOIN dbo.payhistory ph ON m.number = ph.number

LEFTJOIN dbo.DebtorCreditCards dc ON dc.number = m.number

LEFTJOIN dbo.pdc p ON p.number = m.number

LEFTJOIN dbo.Customer c ON c.Customer = m.Customer

LEFTJOIN Apex_ReportingServer.dbo.FeeGoal fg ON fg.CustomerID = c.Customer

GROUP BYm.customer,

c.name,

c.customer,

c.state,

c.FeeSchedule,

m.Branch,

ph.OverPaidAmt,

ph.systemmonth,

ph.datepaid,

ph.totalpaid,

ph.batchtype,

m.desk,

ph.UID,

m.number,

dc.amount,

p.amount,

m.original ,

ph.systemmonth,

ph.systemyear,

ph.ForwardeeFee

HAVINGph.systemmonth = datepart(mm, getdate()) AND ph.batchtype <> 'DA' AND

ph.batchtype <> 'DAR' AND ph.systemyear = datepart(yy, getdate())

AND (c.Name is not null AND c.Name <> '')

ORDER BY m.customer

|||? Hi dba123, Thanks - but you didn't post CREATE TABLE and INSERT statements, so I still can't test any code, nor see what exactly you try to do. Anyway - I'll respond to your other post; it looks to be a simplified version of this problem. If you do need more help in this thread, then add some CREATE TABLE and INSERT statements and expected results, and I'll have a look at it. -- Hugo Kornelis, SQL Server MVP <dba123@.discussions.microsoft.com> schreef in bericht news:662f6401-ea73-4c37-a98e-dd9267c0ed2c@.discussions.microsoft.com... thanks for the heads up. Here's the entire query...and a new attept at fee1 INSERT INTO ReportingServer.dbo.DCR SELECT m.customer, c.name, c.customer, c.state, CASE WHEN Len(c.FeeSchedule) < 3 THEN CONVERT(int, c.feeSchedule) WHEN Len(c.FeeSchedule) > 3 THEN SELECT fd.Fee1 FROM FeeScheduleDetails fd where c.feeSchedule = fd.code AND m.original BETWEEN fd.LowLimit AND fd.HighLimit ELSE CONVERT(int, c.feeSchedule) END AS FeeSchedule, m.Branch, CASE WHEN ph.batchtype = 'PUR' OR ph.batchtype = 'PAR' OR ph.batchtype = 'PCR' Then (ph.totalpaid - ph.ForwardeeFee) ELSE 0.00 END AS [Posted Amount], ph.systemmonth, ph.datepaid, ph.totalpaid, ph.batchtype, m.desk, 0 AS [New Old CC], 0 AS [New Old PDC], 'In-House' AS Type, 1 AS Active, ph.UID, m.number, dc.amount CC, p.amount AS PDC, m.original, CONVERT(money, ph.OverPaidAmt), 0, 0, '' FROM dbo.Master m (NOLOCK) LEFT JOIN dbo.payhistory ph ON m.number = ph.number LEFT JOIN dbo.DebtorCreditCards dc ON dc.number = m.number LEFT JOIN dbo.pdc p ON p.number = m.number LEFT JOIN dbo.Customer c ON c.Customer = m.Customer LEFT JOIN Apex_ReportingServer.dbo.FeeGoal fg ON fg.CustomerID = c.Customer GROUP BY m.customer, c.name, c.customer, c.state, c.FeeSchedule, m.Branch, ph.OverPaidAmt, ph.systemmonth, ph.datepaid, ph.totalpaid, ph.batchtype, m.desk, ph.UID, m.number, dc.amount, p.amount, m.original , ph.systemmonth, ph.systemyear, ph.ForwardeeFee HAVING ph.systemmonth = datepart(mm, getdate()) AND ph.batchtype <> 'DA' AND ph.batchtype <> 'DAR' AND ph.systemyear = datepart(yy, getdate()) AND (c.Name is not null AND c.Name <> '') ORDER BY m.customer|||So are you asking for my table structure then? The table has already been created...so are you asking for the erd ?|||

I am not sure what you are asking. I have also never seen a CASE statement used in this way. CASE statements are always used within a SELECT clause to select a result value to display in the column based on the value in a particular row. SQL has an IF condition of form:

IF.....

BEGIN

END

ELSE

BEGIN

END

Firstly I suggest you use IF that instead. Is your IF statement returning multiple values, or just one value? If it is just returning one value (and with a count(*) you normally only return one valuer, unless using a GROUP BY) then use and IF, otherwise use a case statement. IF example below)

declare @.result int

declare @.lowlimit int

declare @.highlimit int

IF Len(c.FeeSchedule) < 3

BEGIN

set @.result = CONVERT(int, c.feeSchedule)

END

ELSE
work out @.lowlimit and @.highlimit here.....

delcare @.cnt int

Select @.cnt = Count(*) FROM FeeScheduleDetails fd
INNER JOIN Master m ON m.FeeSchedule = fd.code

IF @.cntBETWEEN @.lowlimit AND @.highlimit

BEGIN

@.result = (get Fee1......)

END

ELSE

BEGIN

@.result = (get m.FeeSchedule.....)

END

END

Otherwise, if you want the second conditional to be a CASE statement, you will need to rewrite it accordingly

Clarity Consulting

|||I don't think you can do a select statment inside of a CASE statement. Store the result in a variable, and then select that in the CASE statement instead if possible. Otherwise, get the value from a JOIN instead, then you just need to select the column in the CASE...WHEN .. THEN statement.|||? Hi dba123, Sorry for the delayed reply... >>So are you asking for my table structure then? The table has already been created...so are you asking for the erd ? What I'm askking you for is a bunch of statements that I can copy and paste into Query Analyzer and run to recreate the problem. To give you a very simplified example: instead of asking "how to get the lowest wage for each department", you'd have to post some SQL: CREATE TABLE Personnel (EmpID int NOT NULL PRIMARY KEY, DeptID int NOT NULL, Wage decimal(7,2) NOT NULL) go INSERT INTO Personnel (EmpID, DeptID, Wage) VALUES (1, 1, 20000) INSERT INTO Personnel (EmpID, DeptID, Wage) VALUES (2, 1, 30000) INSERT INTO Personnel (EmpID, DeptID, Wage) VALUES (3, 2, 15000) INSERT INTO Personnel (EmpID, DeptID, Wage) VALUES (4, 3, 20000) go And then, you'd add the required results: DeptID LowestWage 1 20000 2 15000 3 20000 Anyone can now copy the SQL statements, execute them in a test database, try some queries and finally come up with this reply: SELECT DeptID, MIN(Wage) AS LowestWage FROM Personnel GROUP BY DeptID Of course, the example above is pretty basic. Your questions (at least the ones I've seen here) are a lot more complex. Trying to answer them without knowing exactly how the tables look (i.e. columns, datatypes, constraints, indexes, defaults, ... everything you'd see in a CREATE TABLE statement), what kind of data is in them (i.e. the INSERT statements) and what results you expect to get makes it more an exercise at guessing, or even mind reading, than an exercise in writing SQL. I'm pretty good at writing SQL. I think I help a lot of people with my skills in this and other forums and groups. But my clairvoyance skills are lousy. In other words: if you don't explain the problem clear enough, you're likely to get no answer or a wrong answer from me - and probably from others as well. From experience, I know that most probles are best explained by posting CREATE TABLE statements, INSERT statements, expected results and a short explanation. Check out www.aspfaq.com/5006 for more information about this and for some techniques that can help you assemble the information for your posts. I hope this helps. -- Hugo Kornelis, SQL Server MVP|||thanks, I was using the case statement to determine which to return back as FeeSchedule. It's dependent on the lenght of a certain field. I the field was>3 I needed to do a lookup else, juse use that field.|||thanks

NNTP User
. Sometimes I don't have all those statements created because the statement I'm working on is it and is my only attempt/approach at the time! Yes, I could have posted some data examples though. Thanks for your explanation.

Monday, March 26, 2012

Help with assigning variables to from a SQL query

I've reconfigured Microsoft's IBS Store shopping cart to function within a small e-commerce website. What I am trying to do is to modify the code slightly in order to use a third party credit card processing center. The situation is this: once the customer clicks the final "check out" button, a stored procedure writes all of the product ordering information into the database. I, then, capture what they're wanting to purchase with the following SQL statement:

Dim strSQL as String = "Select orderID, modelNumber from orderDetails" & _
"where CustomerID = " & User.Identity.Name & _
"And orderid = (SELECT MAX(orderid)FROM orderDetails" & _
"where CustomerID = " & User.Identity.Name & ")"

What I would like to do is assign specific values to variables based off of the above query. For example:

Dim orderItem as String = (all of the modelNumbers from the query)
Dim orderIdItem as String = (all of the orderIDs from the query)

How do I do this?? Any help is much appreciated! Thanks in advance.

RonI'm not fluent in VB, but try to grasp the outline of the code :)

[code]
Dim myConnection As SqlConnection = New SqlConnection("..my connection string..")
Dim myCommand As SqlCommand = New SqlCommand("the query...")
myCommand.Connection = myConnection
myConnection.Open()
Dim myReader As SqlDataReader = myCommand.ExecuteReader()

'String Builder objects speed up performance, as strings are immutable.
Dim modelNumbers As System.Text.StringBuilder = New System.Text.StringBuilder
Dim orderID As System.Text.StringBuilder = New System.Text.StringBuilder

' Go through all the rows of the query
While (myReader.Read())
modelNumbers.Append(myReader.GetString(0)) 'Add the ModelNumber of the row to the string
orderID.Append(myReader.GetString(1)) ' Add the OrderID of the row to the string
End While

myReader.Close()
myConnection.Close()
[/code]

HTH|||Thanks for your help.

The code creates this error: "Specified cast is not valid", from the following line:

modelNumbers.Append(myReader.GetString(0)) 'Add the ModelNumber of the row to the string

Any ideas?

Again, thanks for your help!

Ron|||The field is either null or its a byte field or something.

I would check if its null first before adding it to the string.

HTH
Tony|||It doesn't come back null. To test this I simply bound the query data to a datagrid in order to display the information on the page. There are no null items; only data...as expected|||Try


modelNumbers.Append(myReader(0).ToString())

Does this help|||This worked beautifully.
Thank you!

Monday, March 12, 2012

Help with "Error 80040e18: Rowset cannot be restarted."

Hi everyone,
The code below runs fine in Access, but in migrating to SQL Server I've run
into this error:
"Microsoft OLE DB Provider for SQL Server error '80040e18'. Rowset position
cannot be restarted."
The code (ASP) is:
#######
If Request.Form("Make") <> "" then
set objCommand = server.CreateObject("ADODB.command")
objCommand.ActiveConnection = objConn
objCommand.CommandText = "usp_ANALYZE_MAKE"
objCommand.CommandType = adCmdStoredProc
objCommand.Parameters.Refresh
objCommand.Parameters(1).Value = Request.Form("Make")
set objRS = objCommand.Execute
set objCommand = Nothing
If Not objRS.EOF then
r = objRS.GetRows
End if
If IsArray(r) Then
intRecordCount = UBound(r, 2) + 1
objRS.MoveFirst
End If
Response.Write "<p><b>Your search returned " & intRecordCount & " result(s)
for: </b></p>"
Response.Write "<blockquote>"
Response.Write "<p><b>Make</b></p>"
Response.Write "</blockquote>"
Response.Write "<p>"
Response.Write "<blockquote>"
Do until objRS.EOF
Response.Write Code Here...
objRS.MoveNext
Loop
Response.Write "</blockquote>"
Response.Write "<p></p>"
objRS.Close
set objRS = Nothing
End If
#######
Is this a case of needing to utilize (based on the above code) a different
cursor, or...? There sure are a lot of differences in how Access and SQL
Server allow you to do things (beyond 'basic' DB structure), or perhaps how
'forgiving' each of them are.
Anyone with a suggestion or workaround? Thanks.
Message posted via http://www.droptable.com
http://support.microsoft.com/kb/174225/en-us
http://groups.google.de/groups?hl=de...07%26rnum%3D11
HTH, Jens Suessmeyer.
http://www.sqlserver2005.de
"The Gekkster via droptable.com" <forum@.nospam.droptable.com> schrieb im
Newsbeitrag news:2723f97d6dc4470492871a765551178f@.droptable.co m...
> Hi everyone,
> The code below runs fine in Access, but in migrating to SQL Server I've
> run
> into this error:
> "Microsoft OLE DB Provider for SQL Server error '80040e18'. Rowset
> position
> cannot be restarted."
> The code (ASP) is:
> #######
> If Request.Form("Make") <> "" then
> set objCommand = server.CreateObject("ADODB.command")
> objCommand.ActiveConnection = objConn
> objCommand.CommandText = "usp_ANALYZE_MAKE"
> objCommand.CommandType = adCmdStoredProc
> objCommand.Parameters.Refresh
> objCommand.Parameters(1).Value = Request.Form("Make")
> set objRS = objCommand.Execute
> set objCommand = Nothing
> If Not objRS.EOF then
> r = objRS.GetRows
> End if
> If IsArray(r) Then
> intRecordCount = UBound(r, 2) + 1
> objRS.MoveFirst
> End If
> Response.Write "<p><b>Your search returned " & intRecordCount & "
> result(s)
> for: </b></p>"
> Response.Write "<blockquote>"
> Response.Write "<p><b>Make</b></p>"
> Response.Write "</blockquote>"
> Response.Write "<p>"
> Response.Write "<blockquote>"
> Do until objRS.EOF
> Response.Write Code Here...
> objRS.MoveNext
> Loop
> Response.Write "</blockquote>"
> Response.Write "<p></p>"
> objRS.Close
> set objRS = Nothing
> End If
> #######
> Is this a case of needing to utilize (based on the above code) a different
> cursor, or...? There sure are a lot of differences in how Access and SQL
> Server allow you to do things (beyond 'basic' DB structure), or perhaps
> how
> 'forgiving' each of them are.
> Anyone with a suggestion or workaround? Thanks.
> --
> Message posted via http://www.droptable.com

Help with "Error 80040e18: Rowset cannot be restarted."

Hi everyone,
The code below runs fine in Access, but in migrating to SQL Server I've run
into this error:
"Microsoft OLE DB Provider for SQL Server error '80040e18'. Rowset position
cannot be restarted."
The code (ASP) is:
#######
If Request.Form("Make") <> "" then
set objCommand = server.CreateObject("ADODB.command")
objCommand.ActiveConnection = objConn
objCommand.CommandText = "usp_ANALYZE_MAKE"
objCommand.CommandType = adCmdStoredProc
objCommand.Parameters.Refresh
objCommand.Parameters(1).Value = Request.Form("Make")
set objRS = objCommand.Execute
set objCommand = Nothing
If Not objRS.EOF then
r = objRS.GetRows
End if
If IsArray(r) Then
intRecordCount = UBound(r, 2) + 1
objRS.MoveFirst
End If
Response.Write "<p><b>Your search returned " & intRecordCount & " result(s)
for: </b></p>"
Response.Write "<blockquote>"
Response.Write "<p><b>Make</b></p>"
Response.Write "</blockquote>"
Response.Write "<p>"
Response.Write "<blockquote>"
Do until objRS.EOF
Response.Write Code Here...
objRS.MoveNext
Loop
Response.Write "</blockquote>"
Response.Write "<p></p>"
objRS.Close
set objRS = Nothing
End If
#######
Is this a case of needing to utilize (based on the above code) a different
cursor, or...? There sure are a lot of differences in how Access and SQL
Server allow you to do things (beyond 'basic' DB structure), or perhaps how
'forgiving' each of them are.
Anyone with a suggestion or workaround? Thanks.
Message posted via http://www.droptable.comhttp://support.microsoft.com/kb/174225/en-us
rnum=11&prev=/ groups%3Fq%3DRowset%2Bcannot%2Bbe%2Brest
arted%2Bmovefirst%26start%3D
10%26hl%3Dde%26lr%3D%26selm%3D%2523NwSu4
7ECHA.1732%2540tkmsftngp07%26rnum%3D11[/ur
l]
HTH, Jens Suessmeyer.
[url]http://www.sqlserver2005.de" target="_blank">http://groups.google.de/groups?hl=d...qlserver2005.de
--
"The Gekkster via droptable.com" <forum@.nospam.droptable.com> schrieb im
Newsbeitrag news:2723f97d6dc4470492871a765551178f@.SQ
droptable.com...
> Hi everyone,
> The code below runs fine in Access, but in migrating to SQL Server I've
> run
> into this error:
> "Microsoft OLE DB Provider for SQL Server error '80040e18'. Rowset
> position
> cannot be restarted."
> The code (ASP) is:
> #######
> If Request.Form("Make") <> "" then
> set objCommand = server.CreateObject("ADODB.command")
> objCommand.ActiveConnection = objConn
> objCommand.CommandText = "usp_ANALYZE_MAKE"
> objCommand.CommandType = adCmdStoredProc
> objCommand.Parameters.Refresh
> objCommand.Parameters(1).Value = Request.Form("Make")
> set objRS = objCommand.Execute
> set objCommand = Nothing
> If Not objRS.EOF then
> r = objRS.GetRows
> End if
> If IsArray(r) Then
> intRecordCount = UBound(r, 2) + 1
> objRS.MoveFirst
> End If
> Response.Write "<p><b>Your search returned " & intRecordCount & "
> result(s)
> for: </b></p>"
> Response.Write "<blockquote>"
> Response.Write "<p><b>Make</b></p>"
> Response.Write "</blockquote>"
> Response.Write "<p>"
> Response.Write "<blockquote>"
> Do until objRS.EOF
> Response.Write Code Here...
> objRS.MoveNext
> Loop
> Response.Write "</blockquote>"
> Response.Write "<p></p>"
> objRS.Close
> set objRS = Nothing
> End If
> #######
> Is this a case of needing to utilize (based on the above code) a different
> cursor, or...? There sure are a lot of differences in how Access and SQL
> Server allow you to do things (beyond 'basic' DB structure), or perhaps
> how
> 'forgiving' each of them are.
> Anyone with a suggestion or workaround? Thanks.
> --
> Message posted via http://www.droptable.com

Help with "Error 80040e18: Rowset cannot be restarted."

Hi everyone,
The code below runs fine in Access, but in migrating to SQL Server I've run
into this error:
"Microsoft OLE DB Provider for SQL Server error '80040e18'. Rowset position
cannot be restarted."
The code (ASP) is:
#######
If Request.Form("Make") <> "" then
set objCommand = server.CreateObject("ADODB.command")
objCommand.ActiveConnection = objConn
objCommand.CommandText = "usp_ANALYZE_MAKE"
objCommand.CommandType = adCmdStoredProc
objCommand.Parameters.Refresh
objCommand.Parameters(1).Value = Request.Form("Make")
set objRS = objCommand.Execute
set objCommand = Nothing
If Not objRS.EOF then
r = objRS.GetRows
End if
If IsArray(r) Then
intRecordCount = UBound(r, 2) + 1
objRS.MoveFirst
End If
Response.Write "<p><b>Your search returned " & intRecordCount & " result(s)
for: </b></p>"
Response.Write "<blockquote>"
Response.Write "<p><b>Make</b></p>"
Response.Write "</blockquote>"
Response.Write "<p>"
Response.Write "<blockquote>"
Do until objRS.EOF
Response.Write Code Here...
objRS.MoveNext
Loop
Response.Write "</blockquote>"
Response.Write "<p></p>"
objRS.Close
set objRS = Nothing
End If
#######
Is this a case of needing to utilize (based on the above code) a different
cursor, or...? There sure are a lot of differences in how Access and SQL
Server allow you to do things (beyond 'basic' DB structure), or perhaps how
'forgiving' each of them are.
Anyone with a suggestion or workaround? Thanks.
--
Message posted via http://www.sqlmonster.comhttp://support.microsoft.com/kb/174225/en-us
http://groups.google.de/groups?hl=de&lr=&threadm=%23NwSu47ECHA.1732%40tkmsftngp07&rnum=11&prev=/groups%3Fq%3DRowset%2Bcannot%2Bbe%2Brestarted%2Bmovefirst%26start%3D10%26hl%3Dde%26lr%3D%26selm%3D%2523NwSu47ECHA.1732%2540tkmsftngp07%26rnum%3D11
HTH, Jens Suessmeyer.
--
http://www.sqlserver2005.de
--
"The Gekkster via SQLMonster.com" <forum@.nospam.SQLMonster.com> schrieb im
Newsbeitrag news:2723f97d6dc4470492871a765551178f@.SQLMonster.com...
> Hi everyone,
> The code below runs fine in Access, but in migrating to SQL Server I've
> run
> into this error:
> "Microsoft OLE DB Provider for SQL Server error '80040e18'. Rowset
> position
> cannot be restarted."
> The code (ASP) is:
> #######
> If Request.Form("Make") <> "" then
> set objCommand = server.CreateObject("ADODB.command")
> objCommand.ActiveConnection = objConn
> objCommand.CommandText = "usp_ANALYZE_MAKE"
> objCommand.CommandType = adCmdStoredProc
> objCommand.Parameters.Refresh
> objCommand.Parameters(1).Value = Request.Form("Make")
> set objRS = objCommand.Execute
> set objCommand = Nothing
> If Not objRS.EOF then
> r = objRS.GetRows
> End if
> If IsArray(r) Then
> intRecordCount = UBound(r, 2) + 1
> objRS.MoveFirst
> End If
> Response.Write "<p><b>Your search returned " & intRecordCount & "
> result(s)
> for: </b></p>"
> Response.Write "<blockquote>"
> Response.Write "<p><b>Make</b></p>"
> Response.Write "</blockquote>"
> Response.Write "<p>"
> Response.Write "<blockquote>"
> Do until objRS.EOF
> Response.Write Code Here...
> objRS.MoveNext
> Loop
> Response.Write "</blockquote>"
> Response.Write "<p></p>"
> objRS.Close
> set objRS = Nothing
> End If
> #######
> Is this a case of needing to utilize (based on the above code) a different
> cursor, or...? There sure are a lot of differences in how Access and SQL
> Server allow you to do things (beyond 'basic' DB structure), or perhaps
> how
> 'forgiving' each of them are.
> Anyone with a suggestion or workaround? Thanks.
> --
> Message posted via http://www.sqlmonster.com

Friday, March 9, 2012

Help using GetColumnInfo()...

Hi, I'm trying to use the following piece of code to obtain the column names from the table in SQL Server, but somehow I'm getting the wrong number of columns in ul_numColumns (see code), and only the first column name in pstr_stringBuffer. Presumably I should be getting a whole string with all the column names there, but I don't. Any suggestions for what I may be doing wrong?..

Thanks in advance

int GetColumnNames(void)

{

try

{

pCommand.CreateInstance(__uuidof (Command));

pCommand->ActiveConnection = pConn;

pCommand->CommandText = "SELECT * FROM t25_pallet_status"; // SQL Syntax...

pRecordset.CreateInstance (__uuidof (Recordset));

pRecordset->CursorLocation = adUseClient;

pRecordset->Open( (IDispatch *) pCommand, vtMissing, adOpenStatic,

adLockReadOnly, adCmdUnknown);

// Get ADORecordsetConstruction interface from the the ADO Recordset

ADORecordsetConstruction *p_adoRecordsetConstruct;

pRecordset->QueryInterface(__uuidof(ADORecordsetConstruction),

(void **)&p_adoRecordsetConstruct);

// From it, we can get the OLEDB <code>IRowset

IRowset *p_rowset;

p_adoRecordsetConstruct->get_Rowset((IUnknown **)&p_rowset);

p_adoRecordsetConstruct->Release(); // don't need it anymore

// The IColumnsInfo that contains ordinals

CComPtr<IColumnsInfo> spColumns;

// Get the the IColumnsInfo from IRowset interface

p_rowset->QueryInterface(&spColumns);

// At this point, we may now release p_rowset

p_rowset->Release();

// IColumnsInfo will give us the DBCOLUMNINFO structure

ULONG ul_numColumns;

DBCOLUMNINFO *p_columnInfo = NULL;

OLECHAR *pstr_stringBuffer = NULL;

// Now get the DBCOLUMNINFO data

spColumns->GetColumnInfo(&ul_numColumns, &p_columnInfo, &pstr_stringBuffer);

// Clean up

CoTaskMemFree(p_columnInfo);

CoTaskMemFree(pstr_stringBuffer);

}

catch(_com_error & ce)

{

PrintComError(ce);

return 0;

}

}

You can do the following to get all the column names

for(ULONG j=0; j<ul_numColumns; j++)

printf("%S\t", p_columnInfo[j].pwszName);

Hope this helps

|||

Thanks a lot Raj,

I kind of sussed it out for my self a short while after I posted the message. I didn't really understand how GetColumnInfo() worked, and I was expecting pstr_stringBuffer to return a string with ALL of the column names (separated by a common delimitter or something). It became apparent to me that I had to loop through and read from a different variable (pwszName) in order to get those names.

I have to say there's very little on examples out there to use functions like this one. Can anyone recomend me a good website where I can get sample code from in C or C++ for the Visual Studio 2003 environment?

Cheers

Wednesday, March 7, 2012

Help to write query...

Hi !

There is one table tCustomers. It has following columns: ID, Name, Code...

By the mistake in this table has appeared incorrect records (duplicates).

How can I write the query to find them ?

I tried:

Select c.ID ID1,s.ID ID2, c.NAME NAME1,s.NAME NAME2, c.Code C1, s.Code C2, From tCustomers c, tCustomers s
where c.Code=s.Code and c.ID <> s.ID

But the result is not that I expected

Hi,

If only the ID field constain duplicates, you can use the following query:

SELECT tCustomers.ID, tCustomers.Name, tCustomers.Code
FROM tCustomers
WHERE (((tCustomers.ID) In (SELECT [ID] FROM [tCustomers] GROUP BY [ID] HAVING Count(*)>1 )))
ORDER BY tCustomers.ID;

If all the fields are duplicated, use the following query:

SELECT tCustomers.ID, tCustomers.Name, tCustomers.Code, Count(tCustomers.ID) NumberOfDups
FROM tCustomers
GROUP BY tCustomers.ID, tCustomers.Name, tCustomers.Code
HAVING (((Count(tCustomers.ID))>1));

Hope this helps

Sunday, February 26, 2012

help SP Code

I type Code in SP

Exec ('INSERT INTO XXX (A,B,C)

Select A,'Y8',C From YYY

GROUP BY A,B');

But it has error, Value 'ABC' not correct

Why, Thanks

William

Exce SP Code have error

Server: Msg 207, Level 16, State 3, Line 1
Invalid column name 'Y8'.

|||

Try this:

EXEC ('INSERT INTO XXX (A,B,C) Select A,''Y8'',C From YYY GROUP BY A,B');

Chris

|||

If you want to use the single quote (‘) with in the sql string you have to use the escape sequence.

Many languages support \ as escape sequential char. But in sql server the same char need to be repeated (twice).

Example:

Select @.a = 'Sql Server''s'

So you have to change your query as follow as,

Exec (

'INSERT INTO XXX (A,B,C)

Select A,''Y8'',C From YYY

GROUP BY A,B'

);

help Simple question

Dear all,
I need to do some analysis on particular records.
For that I have one Table named EVENT in which I have a field named CODE.
From that field value I can get many entries with same CODE value.
Is there a way to extract the value of CODE field which occurs more often in
a table ?
thanks
regards
SergeHi
create table #test
(
col int not null primary key,
code int
)
insert into #test values (1,100)
insert into #test values (2,100)
insert into #test values (3,200)
insert into #test values (4,100)
insert into #test values (5,200)
insert into #test values (6,800)
select top 1 code,count(*)as occur from #test
group by code
order by occur desc
"serge calderara" <sergecalderara@.discussions.microsoft.com> wrote in
message news:2FC5F7A1-C1F4-4033-82B9-8F84EF8FFDD7@.microsoft.com...
> Dear all,
> I need to do some analysis on particular records.
> For that I have one Table named EVENT in which I have a field named CODE.
> From that field value I can get many entries with same CODE value.
> Is there a way to extract the value of CODE field which occurs more often
> in
> a table ?
> thanks
> regards
> Serge

Friday, February 24, 2012

Help sending email

My code below works fine when run from my pc (changed all the values for
obvious reasons). The code is placed inside a DTS task via VBS scripting.
But when I try to run directly from the server where sqlserver is installed,
the script fails.

I have SMTP running, but there is no outlook installed.

Can someone please advise what I am missing.
Thanks
Bob

Set objEmail = CreateObject("CDO.Message")

objEmail.From = "send@.test.com"
objEmail.To = "receive@.test.com"
objEmail.Subject = "TEST SUBJECT"
objEmail.AddAttachment "\\server\test.csv"
objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configu
ration/sendusing") = 2
objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configu
ration/smtpserver") = "SERVER_NAME"
objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configu
ration/smtpauthenticate") = 1
objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configu
ration/sendusername") = "username"
objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configu
ration/sendpassword") = "userpwd"
objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configu
ration/smtpserverport") = 25
objEmail.Configuration.Fields.Update
objEmail.Send

set objEmail = nothingHi B

One thing you might try is change

> objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configu
> ration/sendusing") = 2
to
> objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configu
> ration/sendusing") = "2"

quotes around the 2.

I spent several hours a week ago trying the very same thing and that made
all the difference.

Also is \\server\test.csv accessible from the server you are running this
on?

Here is the full text of the DTS Package I wrote. Note that I don't think
all the fields you included are necessary.

'************************************************* *********************
' Visual Basic ActiveX Script
'************************************************* ***********************

Function Main()
email_alert "dchristo@.yahoo.com", "George_Bush@.whitehouse.gov","Test
Subject", "Test Body"
Main = DTSTaskExecResult_Success
End Function

Sub email_alert(strTo, strFrom, strSubject, strBody)
Dim iConf 'As CDO.Configuration
Dim imsg 'As CDO.Message
Dim flds

Set imsg = CreateObject("CDO.Message")
Set iConf = CreateObject("CDO.Configuration")

Set flds = iConf.Fields

'The http://schemas.microsoft.com/cdo/configuration/ namespace defines
the majority of fields used to set configurations for various CDO objects.
We set and update the following three fields (SendUsing, SMTP_SERVER, and
TimeOut) of the Configuration object:

With flds
.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") =
"2"
.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") =
"smtp-server.mn.rr.com"
.Item("http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout")
= 10
.Update
End With

Set imsg.Configuration = iConf
imsg.To = strTo
imsg.From = strFrom
imsg.Subject = strSubject
imsg.TextBody = strBody
imsg.AddAttachment "c:\log\myfile.txt"
imsg.Send
End Sub
--
-Dick Christoph

"B" <no_spam@.no_spam.com> wrote in message
news:KsydnTnYtfFV2wbZnZ2dnUVZ_uqdnZ2d@.rcn.net...
> My code below works fine when run from my pc (changed all the values for
> obvious reasons). The code is placed inside a DTS task via VBS scripting.
> But when I try to run directly from the server where sqlserver is
> installed,
> the script fails.
> I have SMTP running, but there is no outlook installed.
> Can someone please advise what I am missing.
> Thanks
> Bob
>
> Set objEmail = CreateObject("CDO.Message")
> objEmail.From = "send@.test.com"
> objEmail.To = "receive@.test.com"
> objEmail.Subject = "TEST SUBJECT"
> objEmail.AddAttachment "\\server\test.csv"
> objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configu
> ration/sendusing") = 2
> objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configu
> ration/smtpserver") = "SERVER_NAME"
> objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configu
> ration/smtpauthenticate") = 1
> objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configu
> ration/sendusername") = "username"
> objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configu
> ration/sendpassword") = "userpwd"
> objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configu
> ration/smtpserverport") = 25
> objEmail.Configuration.Fields.Update
> objEmail.Send
> set objEmail = nothing|||Follow-up to my original post below.

Is it possible for the "objEmail.To" to lookup the values from a sqlserver
table?

At the moment, I type the email address separated by a semi-colon.

TIA~

"B" <no_spam@.no_spam.com> wrote in message
news:KsydnTnYtfFV2wbZnZ2dnUVZ_uqdnZ2d@.rcn.net...
> My code below works fine when run from my pc (changed all the values for
> obvious reasons). The code is placed inside a DTS task via VBS scripting.
> But when I try to run directly from the server where sqlserver is
installed,
> the script fails.
> I have SMTP running, but there is no outlook installed.
> Can someone please advise what I am missing.
> Thanks
> Bob
>
> Set objEmail = CreateObject("CDO.Message")
> objEmail.From = "send@.test.com"
> objEmail.To = "receive@.test.com"
> objEmail.Subject = "TEST SUBJECT"
> objEmail.AddAttachment "\\server\test.csv"
objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configu
> ration/sendusing") = 2
objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configu
> ration/smtpserver") = "SERVER_NAME"
objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configu
> ration/smtpauthenticate") = 1
objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configu
> ration/sendusername") = "username"
objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configu
> ration/sendpassword") = "userpwd"
objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configu
> ration/smtpserverport") = 25
> objEmail.Configuration.Fields.Update
> objEmail.Send
> set objEmail = nothing|||Hi B,

Well not directly but you could create an ADODB Command, Connection and
Recordset and use the command to return you a recordset from the Database
that would have 1 or many email addresses that you could concatenate
together and stick in the objEmail.To field.

--
-Dick Christoph
"B" <no_spam@.no_spam.com> wrote in message
news:c4mdnfssT45ImT7ZnZ2dnUVZ_r-dnZ2d@.rcn.net...
> Follow-up to my original post below.
> Is it possible for the "objEmail.To" to lookup the values from a sqlserver
> table?
> At the moment, I type the email address separated by a semi-colon.
> TIA~
>
> "B" <no_spam@.no_spam.com> wrote in message
> news:KsydnTnYtfFV2wbZnZ2dnUVZ_uqdnZ2d@.rcn.net...
>> My code below works fine when run from my pc (changed all the values for
>> obvious reasons). The code is placed inside a DTS task via VBS
>> scripting.
>> But when I try to run directly from the server where sqlserver is
> installed,
>> the script fails.
>>
>> I have SMTP running, but there is no outlook installed.
>>
>> Can someone please advise what I am missing.
>> Thanks
>> Bob
>>
>>
>> Set objEmail = CreateObject("CDO.Message")
>>
>> objEmail.From = "send@.test.com"
>> objEmail.To = "receive@.test.com"
>> objEmail.Subject = "TEST SUBJECT"
>> objEmail.AddAttachment "\\server\test.csv"
>>
> objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configu
>> ration/sendusing") = 2
>>
> objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configu
>> ration/smtpserver") = "SERVER_NAME"
>>
> objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configu
>> ration/smtpauthenticate") = 1
>>
> objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configu
>> ration/sendusername") = "username"
>>
> objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configu
>> ration/sendpassword") = "userpwd"
>>
> objEmail.Configuration.Fields.Item("http://schemas.microsoft.com/cdo/configu
>> ration/smtpserverport") = 25
>> objEmail.Configuration.Fields.Update
>> objEmail.Send
>>
>> set objEmail = nothing
>>
>>

Sunday, February 19, 2012

Help required in ASP.NET code

I am writting a very simple ASP.NET code, I am simlply trying toestablish a connection with the database in SQL Server 2000 and thanclosing the connection but still I am getting an exception,the name ofthe database is mydatabase, SQL Server 2000 is running in the windowsauthenticationfiltered=SSPI. The name of SQL Server 2000 runningonfiltered=xyz,
I checked the name from SQL Server Service Manager.Also I would like tostate here that I also tryed to establish a connection using C# and theconnection was successfully establish which means that there is noproblem with SQL Server also I sucessfully established the connectionwith MS Access and my ASP.NET application which proves that there is noproblem with IIS also.Also please check that the connection stringwhich I am providing is correct or not.The exception which I am gettingis as follows:
////////////

///////////////////////////////////////////////////////////////////
An exception occured while establishing connection
Login failed for user 'xyz\ASPNET'.
////////////////////////////////////////////////////////////////////////////
Please also note that I have a user with the name xyz/Administrator inthe logins of Sql Server 2000. Also note one more thing that the nameof my PC is xyz, I think that there is some problem with the connectionstring which i am providing so please especially check the connectionstring that either I have missed some thing or some thing has gonewrong,also please tell that are there any security restructions forASP.NET to access SQL Server 2000 or some thing like that which I haveto remove.The code is as follows:
//////////////////////////////////////////////////////////////////////////////////////
<%@. Page Language="C#" %>
<%@. Import Namespace="System.Data" %>
<%@. Import Namespace="System.Data.SqlClient" %>
void Page_Load(Object sender , EventArgs e)
{
try
{
SqlConfiltered=new SqlConnection("server=xyz;Integrated Security=SSPI;database=mydatabase;");
connection.Open();
Response.Write("<b>Connection is successfully established</b>");
connection.Close();
}
catch(Exception ex)
{
Response.Write("<b>An exception occured while establishing connection</b><br>"+" "+ex.Message.ToString());
}
}
</Script
The same above code is also present in the attachement file data.aspx ,please guide me where I am making mistake and please tell me that howcan I correct this mistake so that the code executes correctly.Alsoplease tell that what things should be included in the connectionstring and also please check the connection string of this code.

Connection string is fine if you intend to use Windows Authentication against SQl Server. User xyz/Administrator being in the logins has nothing to do with the error since you probably use that when connecting to SQL Server while working with Enterprise Manager interactively (e.g you use EM)

You have specified in connection string (Integrated Security=SSPI) that the Windows Identity ASP.NET runs under will also be used to log in to the given SQL Server instance. Your ASP.NEt application runs under "'xyz\ASPNET" identity which the error message

An exception occured while establishing connection
Login failed for user 'xyz\ASPNET'.

tries to indicate. Therefore this user should have its own login created to the SQL Server and again granted access to themydatabasedatabase given in the connection string.

What you need to do is to give this user the login and adequate permissions to the SQL Server instance by using SQL Server's management tools (Enterprise Manager)