Showing posts with label following. Show all posts
Showing posts with label following. Show all posts

Friday, March 30, 2012

how to construct dynamic sql in stored procedure

Hi Guys.

I want to construct a SQL in stored procedure in the following way. Please guide me how to achive this

CREATE PROCEDURE P_SAMPLE

(

@.P_ONE NVARCHAR(240)

)

AS

BEGIN

DECLARE

@.TMP_CNT INT

BEGIN

EXEC ('SELECT @.TMP_CNT = 1')

-- PRINT @.TMP_CNT

END

END

Regards

Mani

Use sp_executesql to pass/retrive the data to/from dynamic sql. Exec won’t help you here.

Code Snippet

DECLARE @.TMP_CNT INT

DECLARE @.SQL as NVarchar(4000)

DECLARE @.Params as NVarchar(4000)

Set @.SQL = N'SELECT @.TMP_CNT = 1'

Set @.Params = N'@.TMP_CNT as Int OUTPUT'

Exec sp_executesql @.SQL, @.Params, @.TMP_CNT OUTPUT

Select @.TMP_CNT

|||

here is one of the best resource in Dynamic sql

http://www.sommarskog.se/dynamic_sql.html

Madhu

Wednesday, March 28, 2012

how to connect to ssis service - The RPC server is unavailable err

Hi
I am trying to connect to ssis service on remote machine using the sql 2005
management studio
I get the following error :
TITLE: Connect to Server
Cannot connect to <servername>.
Connect to SSIS Service on machine "<servername>" failed:
The RPC server is unavailable.
What do I miss please help
Best regards
Meron FridmanDid you figure out a solution ' I have the same problem
--
homebre
----
homebrew's Profile: http://www.dbtalk.net/m5
View this thread: http://www.dbtalk.net/t29008|||I've got the same problem in a two-node active/active environment.
Anyone got any further info?
"homebrew" wrote:
> Did you figure out a solution ' I have the same problem.
>
> --
> homebrew
> ---
> homebrew's Profile: http://www.dbtalk.net/m55
> View this thread: http://www.dbtalk.net/t290084
> .
>|||I found out that one of our developers (developer #1) wasn't having an
problems, and that he had used a different disk to install on hi
desktop. So then developer #2 used his disk, and her problem went away
I had already put in a call to Microsoft, and we tested my RPC port
and they seemed fine. So I think I got a bad disk ... perhaps som
file is corrupted ?
Then he had another utility for me to try, but I haven't bothered yet
since I'm pretty sure it's the disk, and not something on my desktop
--
homebre
----
homebrew's Profile: http://www.dbtalk.net/m5
View this thread: http://www.dbtalk.net/t29008sql

how to connect to ssis service - The RPC server is unavailable err

Hi
I am trying to connect to ssis service on remote machine using the sql 2005
management studio
I get the following error :
TITLE: Connect to Server
Cannot connect to <servername>.
Connect to SSIS Service on machine "<servername>" failed:
The RPC server is unavailable.
What do I miss please help
Best regards
Meron Fridman
Did you figure out a solution ? I have the same problem.
homebrew
homebrew's Profile: http://www.dbtalk.net/m55
View this thread: http://www.dbtalk.net/t290084

how to connect to ssis service - The RPC server is unavailable err

Hi
I am trying to connect to ssis service on remote machine using the sql 2005
management studio
I get the following error :
TITLE: Connect to Server
Cannot connect to <servername>.
Connect to SSIS Service on machine "<servername>" failed:
The RPC server is unavailable.
What do I miss please help
Best regards
Meron FridmanDid you figure out a solution ' I have the same problem.
homebrew
---
homebrew's Profile: http://www.dbtalk.net/m55
View this thread: http://www.dbtalk.net/t290084|||I found out that one of our developers (developer #1) wasn't having any
problems, and that he had used a different disk to install on his
desktop. So then developer #2 used his disk, and her problem went away.
I had already put in a call to Microsoft, and we tested my RPC ports
and they seemed fine. So I think I got a bad disk ... perhaps some
file is corrupted ?
Then he had another utility for me to try, but I haven't bothered yet,
since I'm pretty sure it's the disk, and not something on my desktop.
homebrew
---
homebrew's Profile: http://www.dbtalk.net/m55
View this thread: http://www.dbtalk.net/t290084

Monday, March 26, 2012

How to connect to SQL Database with C#?

Hi, I am trying to connect to an SQL Database with my C# program, and am having the following problems.

1) Sometimes it connects fine, other times it fails to connect. I am using Integrated Security / Windows Login.

2) I am trying to pass a Select Statement (Which works from SQL Server Management Studio), but it doesn't seem to work in my program. My code doesn't appear to do anything really...

3) When I use only the code that was generated by VS, it loads all the information into the dataGridView, but I want to filter it using the Select Statement.

Here is the code generated by VS:

private void Form1_Load(object sender, EventArgs e)
{
this.collectionTableAdapter.Fill(this.DBDataSet.Collection);
}

Here is my code:

Code Snippet

private void Form1_Load(object sender, EventArgs e)
{
//Connect to the database for Collections Table
SqlConnection thisConnection = new SqlConnection(@."Server=(local)\sqlexpress;Integrated Security=True;" +
"Database=DB");

//Create DataAdapter Object
SqlDataAdapter thisAdapter = new SqlDataAdapter("SELECT Number AS [#], Image1 AS [Image], Title1 AS [Title], Issue1 AS [Issue] FROM Table1 WHERE Tab = 'Tab1'", thisConnection);

//Create DataSet to contain related data tables, rows, and columns
DataSet thisDataSet = new DataSet();

//Fill DataSet using query defined previously for DataAdapter
thisAdapter.Fill(thisDataSet, "Collection");
foreach (DataRow theRow in thisDataSet.Tables["Collection"].Rows)
{
Console.WriteLine(theRow["Number"] + "\t" +
theRow["Image1"] + "\t" +
theRow["Title1"] + "\t" +
theRow["Issue1"]);
}

//Close Connection
thisConnection.Close();
}

One other thing, I don't know if this helps, but it appears that more often than not, it fails to log in to the database when I open the application the first time. If I exit out of the failure notice, then open the application again, it loads the data into the dataGridView (Not the data I want mind you, but at least I can connect to the database... lol).

Thank you.
|||

the very first thing you need to check is the connection string....

Refer : http://www.connectionstrings.com/?carrier=sqlserver2005

And also check the user /login credential

Madhu

|||What error you get when it fails to connect?|||Thank you, I will take a look at that. I have read a lot about this, but for whatever reason have had no luck getting this to work.

Here are the error messages I am getting. I sometimes log in to the server fine, usually on a second attempt, when I can't login I get one of these errors.

1) Cannot open database "DB" requested by the login. The login failed.
Login failed for user '__'.

2) Unhandled exception has occurred in your application. If you click Continue, the application will ignore this error and attempt to continue. If you click Quit, the application will close immediately.

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.

Thank you.
|||

Try to set timeout=0 in web.config and also set query time out=0 in sql server.

See this http://www.aspnettutorials.com/tutorials/database/connect-sql-datasource-csharp.aspx link for relevant connection infrmation.

|||Thanks, I'll give that a shot and take a look at that link. Does it matter that this is an application, not a website?

Thank you.

|||I'm sorry, I'm still very confused by this. Where should I put the timeout = 0? Isn't it important to have a timeout period? Shouldn't it be able to access the database within the timeout period? Should I delete the dataGridView and associated controls that VS added to my project automatically? I'm not sure what I should be doing. I enter the code in as examples outline, but it still doesn't do anything. Here is my most recent code:

private void Form1_Load(object sender, EventArgs e)

string strCon = @."Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Resources\DB.mdf;Integrated Security=True;User Instance=True";

string strSQL = “select * from table1”;

SqlDataAdapter dataAdapter = new SqlDataAdapter(strSQL, strCon);

SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);

// Populate a new data table and bind it to the BindingSource.

DataTable table = new DataTable();

table.Locale = System.Globalization.CultureInfo.InvariantCulture;

dataAdapter.Fill(table);

dbBindingSource.DataSource = table;

// Resize the DataGridView columns to fit the newly loaded content.

dataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);

// you can make it grid readonly.

dataGridView1.ReadOnly = true;

// finally bind the data to the grid

dataGridView1.DataSource = dbBindingSource;

Thank you.


|||I have also tried this:

Code Snippet

// create an open the connection
SqlConnection conn =
new SqlConnection(@."Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Resources\DB.mdf;Integrated Security=True;User Instance=True");

conn.Open();

// create a SqlCommand object for this connection
SqlCommand command = conn.CreateCommand();
command.CommandText = "SELECT Number AS [#], Image AS [Image], Title AS [Title], FROM table1 WHERE Tab = '1'";
command.CommandType = CommandType.Text;

// execute the command that returns a SqlDataReader
SqlDataReader reader = command.ExecuteReader();

// display the results
while (reader.Read())
{
string output = reader.ToString();
Console.WriteLine(output);
}

// close the connection
reader.Close();
conn.Close();

This didn't work either.
|||

Try this:

SqlConnection conn = new SqlConnection("Data Source=localhost; Integrated Security=SSPI; Initial Catalog=pubs");

Replace "Localhost" with your server name, if you have a named instance try giving it in single codes.

|||Hi and thank you very much for your response. I tried that and get this error:

Cannot open database "pubs" requested by the login. The login failed.
Login failed for user '_'.

I tried replacing "pubs" with my database name, but that gave me the same error. I don't understand this. No matter what I do I don't seem to be able to get this to work. What is SSPI by the way?

Thank you.
|||

Alright, thats looks ok

Connect to SQL Server 2005 MS go to security >> logins >> check your windows userid exists in there (hoepfully yes if your server is on the same machine, but still check once) >> right click on the user id >> click on properties >> check what all database rights that user id has >> if your target DB is not checked give the acecss >> select the role you want to give if required or leave it as is if you can live with public role

|||o SSPI is Security Support Provider Interface|||O.K., thank you very much for your help. I followed your instructions and am not entirely sure what I am looking at.

I have several users under Login:

My name and computer login is Michael. The following shows up as a login:

MICHAEL\SQLServer2005MSSQLUser$MICHAEL$SQLEXPRESS

I clicked on Properties of this user and selected User Maping, which listed several databases. I checked the box for this database and it was set to Public.

Is all this going to be necessary if I install this application on another machine? I would like to make this able to be easily distributable. Should I not use the Windows Login?

Thank you.

|||

Well that is all up to what roles you want to have, how you want to setup the security for SQL Server or your application considering the options provided by Microsoft in DOT NET and also in SQL Server.

But lets get on to the main point, doing that help you getting connected to the database thru your application?

sql

How to connect to my MSDE 2000 Rel A

Hi,

I only have Framework installed on my machine, and I also installed MSDE 2000 Rel. A, using the following command:
C:\MSDERelA\setup.exe SAPWD="myPass" INSTANCENAME="myXP"

I can see that the service for this app is running. Though, I could not connect to it using oSql command like the following:
osql -S(local)\myXP -E
or
osql -S(local)\myXP -Usa, and supply the password "myPass".

The message was:
[DBMSLPCN]SQL Server does not exist or access denied.
[DBMSLPCN]ConnectionOpen (Connect()).

Any response would be appreciated.



Subi_IHave you tried
osql -L
to verify the instance name?

If that doesn't help you may also want to check out this link|||Hi McMurdo,

Thanks. The command did help to find my database (my initial post was wrong in specifying the instance name).
And the link really helps for managing MSDE without UI tools.

Thanks,



Subi_I

how to connect to a local sql server on your laptop?

i have problems connecting to the local server on my laptop. i ahve used the following code but it gives me an error saying login flaied for user "sa" or "sekhar".

i tried using the username and password i use to log onto my computer. but it doesnt work.
can anyone tell me how to do it?

the code is typed is

connection = new sqlconnection("server=localhost;uid=sekhar;pwd=sekhar;database=chandu")
..................
.............................
........................
connection.open()..............i have all the next statements correct.
my username is sekhar and the password is sekhar too but it gives me an error.
somebody help me

Thank you

sekhartry using server=(local)

and whether you need the password or not depends on how the SQL Server is set up. does the users view show a user called 'sekhar'? no? when you right click the server node and go to properties->security, does it show windows auth only, or Windows and SQL Server auth?

Friday, March 23, 2012

How to connect remote SQL Server?

I wnat to connect to remote sql server 2005, I do the following steps:

Enable remote connections on the instance of SQL Server that you want to connect to from a remote computer.
Turn on the SQL Server Browser service.
Configure the firewall to allow network traffic that is related to SQL Server and to the SQL Server Browser service.

sp_addlogin 'Wind','ack@.123','db'

but still can't login,tips as follwing:

Login failed for user 'Wind',The user is not associated with a trusted SQL Server connection.

Error:18452

Why? Must use "SQL Server Authentication" connect?

YOu are trying to connect with SQL Server Authenitcation, but you only have Windows Authentication enabled. See the Screencast on my site for more information how to switch the Authentication mode.

Jens K. Suessmeyer

http://www.sqlserver2005.de

Monday, March 12, 2012

How to configure a Database both, as a Publisher and a Subscriber ?

Hi ,
I am using merge replication wherein we have the following architecture.
We have three different databases. One DB acts as the back office server. The second acts as the desktop DB and the last one is a mobile DB i.e. SQLCE DB.
Data needs to be synchronized between the back office server and the desktop. The SQL CE database connects to the desktop for data synchronization. i.e.
I want to push and pull data from the mobile DB to the desktop DB. Hence, here the Desktop DB acts as the Publisher, and the SQL CE DB acts as subscriber.
Further, the desktop DB needs to push and pull data from the back office DB. Hence, in this case, the Desktop DB acts as the subscriber to the Server, and the back office DB acts as publisher.

Merge replication is not allowing me to make the desktop DB as publisher as well as the subscriber at the same time.

Is there any way we can accomplish this?

Thanks in advance.
Regards,
Pushkar.Hi,

Open the SQL Enterprise manager and select the distributor SQL server.
Select the replication option in the tools menu.
Select the option Configure publishers, subscribers and distributors.

Remember to declare all the involved SQL servers on the Distributor (!) via the Client Network Utility (a small program which is installed together with SQL server)

Success, VincentJS

How to Concatonate with Fixed Starting Positions

I want to concatonate the following into ColumnReference
ColumnA + ColumnB + ColumnC + ColumnD
Each of these columns A-D may be variable in length, (but would never
exceed the position in the string I have provided). I would like to store
the values in ColumnReference in the following manner.
ColumnA always begins at position1
ColumnB always begins at position 9
ColumnC always begins at position 13
ColumnD always begins at position 20
Thanks !Rob,
Essentially you need to pad with spaces (unless you wanted other
characters), truncate to length required and concatenate, as in
select ColumnReference =
left((ColumnA + replicate (' ', 8)), 8) +
left((ColumnB + replicate (' ', 4)), 4) +
left((ColumnC + replicate (' ', 7)), 7) +
left((ColumnD + replicate (' ', x)), x)
Replace x with appropriate value (you did not supply the ending position of
ColumnD). Note that the first parameter of the replicate() fn is a space
char (might go unnoticed). I am also assuming all four columns are of the
char family; if not convert as appropriate.
Hope this helps,
Raj
"Rob" <rwc1960@.bellsouth.net> wrote in message
news:yT3ke.18258$J25.12328@.bignews6.bellsouth.net...
>I want to concatonate the following into ColumnReference
> ColumnA + ColumnB + ColumnC + ColumnD
> Each of these columns A-D may be variable in length, (but would never
> exceed the position in the string I have provided). I would like to store
> the values in ColumnReference in the following manner.
> ColumnA always begins at position1
> ColumnB always begins at position 9
> ColumnC always begins at position 13
> ColumnD always begins at position 20
> Thanks !
>|||You can pad and concatenate strings in SQL, but a better question is
why are you destroying and doing formatting in the database?

Wednesday, March 7, 2012

How to compare chinese words/signs in a sql-statement?

I have the following line of (delphi)code:

SQL.Add('SELECT Language_ID FROM Languages WHERE Language_Name = :language');
ADOQuery2.Parameters.ParamByName('language').Value := TntComboBox1.Text;

TntComboBox1.Text is an widestring with chinese marks, which it got from the same database.

After more then an hour, i used the query analyzer and i saw, MS SQL cant compare chinese signs. (its not delphi's fault, i tested)

Must i change some settings? And where?
I can insert the chinese language and put in a table for example, without a problem...

thnx,
ErikAre your field types set to unicode NCHAR and NVARCHAR?

blindman|||Yes, i have, otherwise i can't insert and select it.
I can't do:
SELECT something FROM table WHERE column_with_chinese_signs = 'chinese_Sign R'
R

only with:
SELECT something FROM table WHERE column_with_chinese_signs = N'chinese_Sign R'

see the N!

but now i can't implement it in Delphi... SQL.ADD('... = N x')
x is a variable (e.g. a sign but can also be a word)

I hpe i was clear

Friday, February 24, 2012

how to combine text data rows into single row?

Hi!!!!

Need some quick help on SQL.....DTS packages.

I’ve loaded data from text files into a table which is in the following format.....

Seq_No

Row_No

Data

1

1

ABC

2

2

DEF

3

3

GHI

4

4

JKL

5

1

MNO

6

2

PQR

7

3

STU

8

4

VWX

Every four lines correspond to one single logical record. So, all the data in every 4 rows have to be combined into one big string which’ll then be loaded into one col of another temporary table .....structure below.....

Record_No

Data

1

ABCDEFGHIJKL

2

MNOPQRSTUVWX

I’m looking for a way to achieve this WITHOUT using Cursors (as it’ll slow down performance)......

Any suggestions will be highly appreciated.

what data type is the Data column?|||

One way is to use the CLR Aggregate function for string concatenation shown in the BOL

http://msdn2.microsoft.com/en-us/library/ms254508.aspx

and then run a query like this

select ((Seq_No-1) / 4)+1 as Record_No, dbo.Concatenate(Data) as Data
into dest
from source
group by ((Seq_No-1) / 4)+1
go

select * from dest
go

|||

hi pramy,

please refer to this post

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=586833&SiteID=1

regards

|||

hi Derek,

thanks for ur reply. the data type is of varchar.

|||

pramy, you still need help on this issue? if not please mark an answer.

thanks,

derek

|||

hi all,

thanks for ur response.

Derek, i've got the solution for my problem and the query is as given below.

select 'data' = convert(varchar(100),(a.data)+''+(b.data)+''+(c.data)+''+(d.data))

from test_data a,test_data b,test_data c,test_data d

where ((b.seqno=a.seqno+1 and b.rowno=a.rowno+1)and(c.seqno=b.seqno+1 and c.rowno=b.rowno+1)and(d.seqno=c.seqno+1 and d.rowno=c.rowno+1))

how to combine text data rows into single row?

Hi!!!!

Need some quick help on SQL.....DTS packages.

I’ve loaded data from text files into a table which is in the following format.....

Seq_No

Row_No

Data

1

1

ABC

2

2

DEF

3

3

GHI

4

4

JKL

5

1

MNO

6

2

PQR

7

3

STU

8

4

VWX

Every four lines correspond to one single logical record. So, all the data in every 4 rows have to be combined into one big string which’ll then be loaded into one col of another temporary table .....structure below.....

Record_No

Data

1

ABCDEFGHIJKL

2

MNOPQRSTUVWX

I’m looking for a way to achieve this WITHOUT using Cursors (as it’ll slow down performance)......

Any suggestions will be highly appreciated.

what data type is the Data column?|||

One way is to use the CLR Aggregate function for string concatenation shown in the BOL

http://msdn2.microsoft.com/en-us/library/ms254508.aspx

and then run a query like this

select ((Seq_No-1) / 4)+1 as Record_No, dbo.Concatenate(Data) as Data
into dest
from source
group by ((Seq_No-1) / 4)+1
go

select * from dest
go

|||

hi pramy,

please refer to this post

http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=586833&SiteID=1

regards

|||

hi Derek,

thanks for ur reply. the data type is of varchar.

|||

pramy, you still need help on this issue? if not please mark an answer.

thanks,

derek

|||

hi all,

thanks for ur response.

Derek, i've got the solution for my problem and the query is as given below.

select 'data' = convert(varchar(100),(a.data)+''+(b.data)+''+(c.data)+''+(d.data))

from test_data a,test_data b,test_data c,test_data d

where ((b.seqno=a.seqno+1 and b.rowno=a.rowno+1)and(c.seqno=b.seqno+1 and c.rowno=b.rowno+1)and(d.seqno=c.seqno+1 and d.rowno=c.rowno+1))

How to Combine results from multiple records into one

Hello,

I have a table which has the following structure:

ID MessageText
001 Hello
001 There
001 Working
003 See
003 you
003 Next
003 Time

How to build a query or store procedure to return result like this:

ID MessageText
001 Hello There Working
003 See you Next Time

Your help/advice is greatly appreciated.

Thanks, FicisaYou don't have anything that would identify the order of the words in the sentence....|||The order is not important, as long as I can put them together into one field.|||USE Northwind
GO

CREATE TABLE myTable99(WordOrder int IDENTITY(1,1), [ID] char(3), MessageText varchar(255))
GO

INSERT INTO myTable99([ID], MessageText)
SELECT '001', 'Hello' UNION ALL
SELECT '001', 'There' UNION ALL
SELECT '001', 'Working' UNION ALL
SELECT '003', 'See' UNION ALL
SELECT '003', 'you' UNION ALL
SELECT '003', 'Next' UNION ALL
SELECT '003', 'Time'
GO

DECLARE @.messagetext varchar(2000), @.MAX_ID char(3), @.MIN_ID char(3)

DECLARE @.myTable99 TABLE ([ID] char(3), messagetext varchar(2000))

SELECT @.MAX_ID = MAX([ID])
, @.MIN_ID = MIN([ID])
FROM myTable99

SELECT @.messagetext = ''

WHILE @.MIN_ID <> @.MAX_ID
BEGIN
SELECT @.messagetext = COALESCE(@.messagetext+ ' ','') + MessageText
FROM myTable99
WHERE [ID] = @.MAX_ID

INSERT INTO @.myTable99([ID], MessageText)
SELECT @.MAX_ID, @.MessageText

SELECT @.MAX_ID = MAX([ID])
FROM myTable99
WHERE [ID] < @.MAX_ID

SELECT @.messagetext = ''
END

SELECT @.messagetext = COALESCE(@.messagetext+ ' ','') + MessageText
FROM myTable99
WHERE [ID] = @.MIN_ID

INSERT INTO @.myTable99([ID], MessageText)
SELECT @.MIN_ID, @.MessageText

SELECT * FROM @.myTable99
GO

DROP TABLE myTable99
GO|||aaaaaaaaaaaarggggh! code!!!

my eyes!!!!! they're BLEEEEEEEEEDING!!

hey, how's this for a solution:

select ID
, group_concat(MessageText) as MessageText
from atable
group
by ID

see GROUP BY functions (http://dev.mysql.com/doc/mysql/en/GROUP-BY-Functions.html)

not sql server?

pity, eh

:cool:|||That's mySQL not SQL Server|||Ok, how about the hybred approach:CREATE TABLE dbo.tMessages (
Id CHAR(3) NOT NULL
, MessageText VARCHAR(20) NOT NULL
)

INSERT dbo.tMessages (Id, MessageText)
SELECT '001', 'Hello'
UNION ALL SELECT '001', 'There'
UNION ALL SELECT '001', 'Working'
UNION ALL SELECT '003', 'See'
UNION ALL SELECT '003', 'you'
UNION ALL SELECT '003', 'Next'
UNION ALL SELECT '003', 'Time'

DROP FUNCTION dbo.fGrunge
GO
CREATE FUNCTION dbo.fGrunge (
@.id CHAR(3)
) RETURNS VARCHAR(4000) AS
BEGIN
DECLARE @.c VARCHAR(20), @.r VARCHAR(8000)
SET @.r = ''

DECLARE zfGrunge CURSOR FOR SELECT MessageText
FROM dbo.tMessages
WHERE id = @.id
ORDER BY MessageText

OPEN zfGrunge
FETCH zfGrunge INTO @.c

WHILE 0 = @.@.fetch_status
BEGIN
SET @.r = @.r + ' ' + @.c
FETCH zfGrunge INTO @.c
END

CLOSE zfGrunge
DEALLOCATE zfGrunge

RETURN SubString(@.r, 2, 8000)
END
GO

SELECT a.id, dbo.fGrunge(a.id)
FROM dbo.tMessages AS a
GROUP BY a.id
ORDER BY a.id

DROP TABLE dbo.tMessages-PatP|||Pat,

A cursor?

Damn, it's only Monday....|||Oh wow,

Perfect!!!

Brett's answer works great. There sure are some programming, it would be nice to have group_concat() function in MS SQL. Forgot I can create one of my own. Thanks very much Pat!!!

Now here's another question, I was trying to use cursor to solve it, like in Pat's function, does it have any disadvantage/advantage over Brett's solution?

Thank you a bunch!!!

ficisa|||I can do it with oodles of left joins, but that gets ugly too. While cursors are a good way to kill an application, they are intent on killing this one anyway.

Trawling the result set is better done on the middle tier or the client anyway. This is fundamentally poor design. I was just offering this as a solution to the stated problem, not necessarily advocating it!

-PatP|||How much data you talking about?

Why not perf bechmark both and let us know...(ya gotta do something...:D )

But I'm thinking (ok, ok, don't all be sooo amazed) that the cursor will be slower...|||Originally posted by Brett Kaiser
That's mySQL not SQL Server

dude, i knew that

(something about grandmothers and eggs)

that's why i posted it!!

so that you sql server guys could SEE HOW IT SHOULD BE DONE

:cool:|||Originally posted by r937
dude, i knew that

(something about grandmothers and eggs)

that's why i posted it!!

so that you sql server guys could SEE HOW IT SHOULD BE DONE

:cool:

Rudy, where is that in the ANSI guide?

I can't find it...

:D|||ansi?

shirley you jest

as if microsoftborg gave two figs for ansi|||Don't call me shirley...

I prefer laverne|||Ok, I tested with my function below and Pat's function using a cursor, with 3436 groups, both took same amount of time of 4 seconds to complete. Hmmm....

So how about this as the function?

CREATE FUNCTION dbo.Group_Concat_Message

(@.InstitutionNumber char(6) )

RETURNS varchar(5000)

AS

BEGIN

DECLARE @.messagetext varchar(5000)

SELECT @.messagetext = COALESCE(@.messagetext+ ' ','') + MessageText
FROM vInstWithMessage
WHERE InstitutionNumber = @.InstitutionNumber

Return @.messagetext

END|||Why not...

Still think you'll end up worrying about the order of the data at some point..

GOOD LUCK...

and OH MY GOD...it's after 5:00!

Later..

How to combine 3 SQL statements into 1?

I have the following 3 SQL statements that need to be combined, if
possible. The output of one feeds the input of the next. I need to view
all of the defined output fields (the output needs to be used in a
Crystal Report).

The SQL Follows:
/* Input is ISBN (vendor_part_number) */
QUERY_1 - returns 1 record
select p.product_id, v.name, m.description, p.author, p.title,
p.revision_number, p.copyright_edition, p.vendor_part_number,
p.conforming_flag,
m.code, mp.unit_price_product, mm.quota_price
from T_PRODUCT p, T_VENDOR v, T_PRODUCT_VENDOR pv,
T_MULTILIST_PRODUCT mp, T_MULTILIST m,
T_MULTILIST_MEMBERSHIP mm where
/* p.vendor_part_number == input */
p.vendor_part_number = '0153364475' and p.medium_type =
'TEXTBOOK' and
p.product_id = pv.product_id and pv.type = 'CONTRACT' and
pv.vendor_id = v.id and
p.product_id = mp.product_id and
m.code = mp.multilist_code and m.proclamation_year =
mp.proclamation_year
and m.proclamation_seq_id = mp.proclamation_seq_id and
m.code = mm.multilist_code and m.proclamation_year =
mm.proclamation_year
and m.proclamation_seq_id = mm.proclamation_seq_id
/* The above should return a single record */

QUERY_2 - returns 2 records
select p.product_id, p.consumable, p.title, p.copyright_edition,
p.vendor_part_number, p.product_type,
p.item_type, p.hardware_required
from T_PRODUCT p, T_PRODUCT_RELATION pr where (pr.relationship_type =
'AID'
or pr.relationship_type = 'KIT') and
p.product_id = pr.child_product_id and pr.parent_product_id =
90321
/* 90321 = result from above: pr.parent_product_id = p.product_id
*/

QUERY_3 - returns 18 records
select p.product_id, p.consumable, p.title, p.copyright_edition,
p.vendor_part_number, p.product_type,
p.item_type, p.hardware_required
from T_PRODUCT p, T_PRODUCT_RELATION pr where (pr.relationship_type =
'AID'
or pr.relationship_type = 'KIT') and
p.product_id = pr.child_product_id and pr.parent_product_id in
(90322, 90323)
/* 90322, 90323 = result from QUERY_2: pr.parent_product_id =
p.product_id */

Only 21 records are returned from these combined queries. I need access
to all of them even though there are 3 different resultsets, 2 of which
contain the same fields. Is there a way to simplify this into a stored
procedure or a view that can take 1 input parameter? It needs to be
used in a Crystal Report, which is limited in its handling of these
types of complex queries.Hi,

Cant you use Derived tables? I havent gone through the queries though.
But generally when I need to query on results from a query, I use a
derived table.

Its something like this...

select * from
(select * from Employee) A

Dont know whether it will work in your case...

Kart

MackTheKnife wrote:

Quote:

Originally Posted by

I have the following 3 SQL statements that need to be combined, if
possible. The output of one feeds the input of the next. I need to view
all of the defined output fields (the output needs to be used in a
Crystal Report).
>
The SQL Follows:
/* Input is ISBN (vendor_part_number) */
QUERY_1 - returns 1 record
select p.product_id, v.name, m.description, p.author, p.title,
p.revision_number, p.copyright_edition, p.vendor_part_number,
p.conforming_flag,
m.code, mp.unit_price_product, mm.quota_price
from T_PRODUCT p, T_VENDOR v, T_PRODUCT_VENDOR pv,
T_MULTILIST_PRODUCT mp, T_MULTILIST m,
T_MULTILIST_MEMBERSHIP mm where
/* p.vendor_part_number == input */
p.vendor_part_number = '0153364475' and p.medium_type =
'TEXTBOOK' and
p.product_id = pv.product_id and pv.type = 'CONTRACT' and
pv.vendor_id = v.id and
p.product_id = mp.product_id and
m.code = mp.multilist_code and m.proclamation_year =
mp.proclamation_year
and m.proclamation_seq_id = mp.proclamation_seq_id and
m.code = mm.multilist_code and m.proclamation_year =
mm.proclamation_year
and m.proclamation_seq_id = mm.proclamation_seq_id
/* The above should return a single record */
>
QUERY_2 - returns 2 records
select p.product_id, p.consumable, p.title, p.copyright_edition,
p.vendor_part_number, p.product_type,
p.item_type, p.hardware_required
from T_PRODUCT p, T_PRODUCT_RELATION pr where (pr.relationship_type =
'AID'
or pr.relationship_type = 'KIT') and
p.product_id = pr.child_product_id and pr.parent_product_id =
90321
/* 90321 = result from above: pr.parent_product_id = p.product_id
*/
>
QUERY_3 - returns 18 records
select p.product_id, p.consumable, p.title, p.copyright_edition,
p.vendor_part_number, p.product_type,
p.item_type, p.hardware_required
from T_PRODUCT p, T_PRODUCT_RELATION pr where (pr.relationship_type =
'AID'
or pr.relationship_type = 'KIT') and
p.product_id = pr.child_product_id and pr.parent_product_id in
(90322, 90323)
/* 90322, 90323 = result from QUERY_2: pr.parent_product_id =
p.product_id */
>
>
Only 21 records are returned from these combined queries. I need access
to all of them even though there are 3 different resultsets, 2 of which
contain the same fields. Is there a way to simplify this into a stored
procedure or a view that can take 1 input parameter? It needs to be
used in a Crystal Report, which is limited in its handling of these
types of complex queries.