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

Tuesday, March 27, 2012

BEST SSIS equivalent for DTS2000 CURSORS

Hi everyone,

Right now we are trying to replace all stored procedures by SSIS logic.

One of the stored procedures does the following,

1. For Every record in PSTREELEAF find the Hierarchy FROM
PSTREENODE and store them in local valriables.

First the stored procedure pulls all the data from the PSTREELEAF table based on join condition into local variables using cursor. Then for every record in the cursor it finds the corresponding records from PSTREENODE table. This is just a part of the stored procedure.

can anyone tell me how can i do this in SSIS? and also tell me which task would be a perfect replacement for CURSORS in SSIS?

Thanks,

Praveen

Hi,
Do not use cursors if you can avoid it and do not attempt to replicate cursors.
Use Set based logic or derived tables or subqueries or Update statements or affect values to columns using subqueries as columns (top 1 or distinct).

Please post some more explicit examples and we may suggest another approach.

you can create loops in SSSI but the point is to make sure you really need this in the first place.

Philippe|||

Hi ,

thanks Phillippe.... here is the code which i need to change it to SSIS logic.

DECLARE NodeCursor CURSOR LOCAL FOR SELECT DISTINCT Tree_node_num,Range_from,Range_to,EFFDT
FROM FINANCEODS.DBO.PSTREELEAF
WHERE TREE_NAME='ACCTROLLUP' AND EffDt>=@.effDt AND INACTIVE_DATE IS NULL

OPEN NodeCursor

/*********************************************************************************
fetch nodes one by one and find out the hierarchy of the nodes
*********************************************************************************/

FETCH NEXT FROM NodeCursor
INTO @.Tree_node_num,@.LeafFrom,@.LeafTo,@.effDt
SET @.Parent_node_num=@.Tree_node_num

IF @.@.ERROR <> 0
BEGIN
ROLLBACK TRANSACTION
SET @.p_errNum = 50505
SET @.p_errMsg = 'SPUpdateAccounts: Error Fetching Node Cursor.'
RETURN Exit Stored Procedure
END
WHILE @.@.FETCH_STATUS = 0
BEGIN
/*****************************************************
While Loop to find out all the Hierarchy information

******************************************************/
WHILE (@.Parent_node_num)<>0

BEGIN

/************************************************************************************
Find the Parent node and its level(hierarchy)
*************************************************************************************/
SELECT @.Parent_node_num=Parent_node_num, @.Tree_node_num=Tree_node_num,@.TreeLevel=TREE_LEVEL_NUM ,@.TreeNode=ISNULL(B.DESCR,A.TREE_NODE)
FROM FINANCEODS.DBO.PSTREENODE A
LEFT JOIN ( SELECT MAX(EFFDT) AS EFFDT,DESCR,TREE_NODE,INACTIVE_DATE FROM FINANCEODS.DBO.PS_TREE_NODE_TBL WHERE EFFDT<
=@.EFFDT GROUP BY DESCR,TREE_NODE,INACTIVE_DATE ) B ON A.TREE_NODE=B.TREE_NODE
WHERE
A.Tree_node_num=@.Tree_node_num
AND A.TREE_NAME='ACCTROLLUP' AND A.EFFDT=@.EFFDT AND A.INACTIVE_DATE IS NULL AND B.INACTIVE_DATE IS NULL
/************************************************************************************
Store the Hierarchy level information in local variables.
*************************************************************************************/
SELECT @.Source= (CASE @.TreeLevel WHEN 6 THEN @.TreeNode ELSE @.Source END),
@.Type= (CASE @.TreeLevel WHEN 5 THEN @.TreeNode ELSE @.Type END),
@.Element= (CASE @.TreeLevel WHEN 4 THEN @.TreeNode ELSE @.Element END),
@.Component= (CASE @.TreeLevel WHEN 3 THEN @.TreeNode ELSE @.Component END),
@.FinStatement= (CASE @.TreeLevel WHEN 2 THEN @.TreeNode ELSE @.FinStatement END)
SET @.Tree_node_num=@.Parent_node_num
END

Sunday, March 25, 2012

Best replication model?

I am looking for some advice/comments on what the best replication model
would be in the following situation:
We have a series of complex (slow) stored procedures that do lots of
calculations but produce relatively few changes in the database. These
stored procedures were written such that they process chunks of data
based on passed in parameters, and it is possible to run the same stored
procedure simultaneously with different parameters without them stepping
on each other's toes. The problem is that it is very CPU intensive.
We were thinking of using replication to replicate the data to several
servers and spreading the processing load between them. Then any
updates to the db produced would get replicated back to all the other
databases. All the databases must be in sync, but some latency is ok.
Would replication be appropriate in this situation? What is the best
replication model here? I was thinking Queued Updating Transactional.
Would welcome any thoughts/comments.
Thanks,
Alek
*** Sent via Developersdex http://www.codecomments.com ***
Don't just participate in USENET...get rewarded for it!
I think you should look at extended stored procedures or even the CLR
functionality which ships with Yukon.
Queued Updating will probably work for this, as long as you have less than
10 subscribers, and the majority of your updates occur on your publisher.
The reason that most updates should occur on your publisher is to minimize
the possibilities of conflicts. If you can guarantee that you won't get
conflicts queued should work.
Hilary Cotter
Looking for a SQL Server replication book?
http://www.nwsu.com/0974973602.html
"Alek B" <developersdex.10.alekb@.spamgourmet.com> wrote in message
news:O8LrOkQ7EHA.2192@.TK2MSFTNGP14.phx.gbl...
>I am looking for some advice/comments on what the best replication model
> would be in the following situation:
> We have a series of complex (slow) stored procedures that do lots of
> calculations but produce relatively few changes in the database. These
> stored procedures were written such that they process chunks of data
> based on passed in parameters, and it is possible to run the same stored
> procedure simultaneously with different parameters without them stepping
> on each other's toes. The problem is that it is very CPU intensive.
> We were thinking of using replication to replicate the data to several
> servers and spreading the processing load between them. Then any
> updates to the db produced would get replicated back to all the other
> databases. All the databases must be in sync, but some latency is ok.
> Would replication be appropriate in this situation? What is the best
> replication model here? I was thinking Queued Updating Transactional.
> Would welcome any thoughts/comments.
> Thanks,
> Alek
> *** Sent via Developersdex http://www.codecomments.com ***
> Don't just participate in USENET...get rewarded for it!

Thursday, March 22, 2012

Best practices to transfer data/tables from TEST to LIVE

HI all,
I'm definately a newbie and have what is probably a simple question
but I want to make sure I'm following good practices.
What is the best way to update a LIVE database with data being created
on a TEST/DEV database?
I want to send a few new records I created on a test environment onto
a live environment to a few different tables. It is only a couple
records and could probably manually do it in like 10 minutes. But I
assume eventually I'll have larger qualities of data to move and
tables to update and I don't want to forget to include soemthing.
What is the best way to handle this kind of stuff? Scripts? Any
other suggestions or different ideas?
Kind Regards,
Ray
You can achieve your goal scripting or using SSIS; scripting could seem the
simplest way for the job you described, but if you think that the same job
could be reused or subsequently implemented, you can build a package using
Business Intelligence Development Studio (BIDS). For more (really more!)
details, look at the Books on Line "SQL Server Integration Services (SSIS)"
chapter.
Gilberto Zampatti
"bcap" wrote:

> HI all,
> I'm definately a newbie and have what is probably a simple question
> but I want to make sure I'm following good practices.
> What is the best way to update a LIVE database with data being created
> on a TEST/DEV database?
> I want to send a few new records I created on a test environment onto
> a live environment to a few different tables. It is only a couple
> records and could probably manually do it in like 10 minutes. But I
> assume eventually I'll have larger qualities of data to move and
> tables to update and I don't want to forget to include soemthing.
> What is the best way to handle this kind of stuff? Scripts? Any
> other suggestions or different ideas?
> Kind Regards,
> Ray
>
|||On Jun 9, 3:24 am, Gilberto Zampatti
<GilbertoZampa...@.discussions.microsoft.com> wrote:
> You can achieve your goal scripting or using SSIS; scripting could seem the
> simplest way for the job you described, but if you think that the same job
> could be reused or subsequently implemented, you can build a package using
> Business Intelligence Development Studio (BIDS). For more (really more!)
> details, look at the Books on Line "SQL Server Integration Services (SSIS)"
> chapter.
> Gilberto Zampatti
>
> "bcap" wrote:
>
>
>
> - Show quoted text -
Thank you very much!

Best practices to transfer data/tables from TEST to LIVE

HI all,
I'm definately a newbie and have what is probably a simple question
but I want to make sure I'm following good practices.
What is the best way to update a LIVE database with data being created
on a TEST/DEV database?
I want to send a few new records I created on a test environment onto
a live environment to a few different tables. It is only a couple
records and could probably manually do it in like 10 minutes. But I
assume eventually I'll have larger qualities of data to move and
tables to update and I don't want to forget to include soemthing.
What is the best way to handle this kind of stuff? Scripts? Any
other suggestions or different ideas?
Kind Regards,
RayYou can achieve your goal scripting or using SSIS; scripting could seem the
simplest way for the job you described, but if you think that the same job
could be reused or subsequently implemented, you can build a package using
Business Intelligence Development Studio (BIDS). For more (really more!)
details, look at the Books on Line "SQL Server Integration Services (SSIS)"
chapter.
Gilberto Zampatti
"bcap" wrote:

> HI all,
> I'm definately a newbie and have what is probably a simple question
> but I want to make sure I'm following good practices.
> What is the best way to update a LIVE database with data being created
> on a TEST/DEV database?
> I want to send a few new records I created on a test environment onto
> a live environment to a few different tables. It is only a couple
> records and could probably manually do it in like 10 minutes. But I
> assume eventually I'll have larger qualities of data to move and
> tables to update and I don't want to forget to include soemthing.
> What is the best way to handle this kind of stuff? Scripts? Any
> other suggestions or different ideas?
> Kind Regards,
> Ray
>|||On Jun 9, 3:24 am, Gilberto Zampatti
<GilbertoZampa...@.discussions.microsoft.com> wrote:
> You can achieve your goal scripting or using SSIS; scripting could seem th
e
> simplest way for the job you described, but if you think that the same job
> could be reused or subsequently implemented, you can build a package using
> Business Intelligence Development Studio (BIDS). For more (really more!)
> details, look at the Books on Line "SQL Server Integration Services (SSIS)
"
> chapter.
> Gilberto Zampatti
>
> "bcap" wrote:
>
>
>
>
>
>
> - Show quoted text -
Thank you very much!

Best practices to transfer data/tables from TEST to LIVE

HI all,
I'm definately a newbie and have what is probably a simple question
but I want to make sure I'm following good practices.
What is the best way to update a LIVE database with data being created
on a TEST/DEV database?
I want to send a few new records I created on a test environment onto
a live environment to a few different tables. It is only a couple
records and could probably manually do it in like 10 minutes. But I
assume eventually I'll have larger qualities of data to move and
tables to update and I don't want to forget to include soemthing.
What is the best way to handle this kind of stuff? Scripts? Any
other suggestions or different ideas?
Kind Regards,
RayYou can achieve your goal scripting or using SSIS; scripting could seem the
simplest way for the job you described, but if you think that the same job
could be reused or subsequently implemented, you can build a package using
Business Intelligence Development Studio (BIDS). For more (really more!)
details, look at the Books on Line "SQL Server Integration Services (SSIS)"
chapter.
Gilberto Zampatti
"bcap" wrote:
> HI all,
> I'm definately a newbie and have what is probably a simple question
> but I want to make sure I'm following good practices.
> What is the best way to update a LIVE database with data being created
> on a TEST/DEV database?
> I want to send a few new records I created on a test environment onto
> a live environment to a few different tables. It is only a couple
> records and could probably manually do it in like 10 minutes. But I
> assume eventually I'll have larger qualities of data to move and
> tables to update and I don't want to forget to include soemthing.
> What is the best way to handle this kind of stuff? Scripts? Any
> other suggestions or different ideas?
> Kind Regards,
> Ray
>|||On Jun 9, 3:24 am, Gilberto Zampatti
<GilbertoZampa...@.discussions.microsoft.com> wrote:
> You can achieve your goal scripting or using SSIS; scripting could seem the
> simplest way for the job you described, but if you think that the same job
> could be reused or subsequently implemented, you can build a package using
> Business Intelligence Development Studio (BIDS). For more (really more!)
> details, look at the Books on Line "SQL Server Integration Services (SSIS)"
> chapter.
> Gilberto Zampatti
>
> "bcap" wrote:
> > HI all,
> > I'm definately a newbie and have what is probably a simple question
> > but I want to make sure I'm following good practices.
> > What is the best way to update a LIVE database with data being created
> > on a TEST/DEV database?
> > I want to send a few new records I created on a test environment onto
> > a live environment to a few different tables. It is only a couple
> > records and could probably manually do it in like 10 minutes. But I
> > assume eventually I'll have larger qualities of data to move and
> > tables to update and I don't want to forget to include soemthing.
> > What is the best way to handle this kind of stuff? Scripts? Any
> > other suggestions or different ideas?
> > Kind Regards,
> > Ray- Hide quoted text -
> - Show quoted text -
Thank you very much!

Best practices to design datawarehouse for a Fraud Detection/Transaction Monitoring Application

Hi All,

This thread relates to following thread of Architecure forum.

http://forums.microsoft.com/msdn/showpost.aspx?postid=1908857&siteid=1&sb=0&d=1&at=7&ft=11&tf=0&pageid=2

Because after reaching at decision that application would require datawarehousing the members suggested that it would be nice if it is posted on datawarehouse forum.

I would appreciate if could go through the mentioned thread that would state application's business requirement.

Now i am continuing the from the thread where we were discussing about SCD.

In our Application customer address is defined in 6 fields (Street,city,State,Country,Pincode,ContactNo) so if we are to maintain 3 type of addresses like Office,Communication,Residence then we have to add 18 fields in our Customer Master dimension table in our dataware house.

Suppose after some time customer office address is changed so what should be done in Customer Master Table at time of synchronization, Should ETL process insert a new record into dimension table with updated address in office address fields or it should update the existing record fields without adding new one.

If for Changing dimensions we are adding a new record then we have to maintain a flag field where status of record would be kept like 'current record' or 'old record' , this would help us to identify the main record.Every time whenever a new customer record is added old record status is changed to 'Old record'.

Should we add new record for changing fields like address,designation,employer,annual income etc or update the existing record only.Because in our analysis these all fields would play major because after each profile updation a risk category is assigned to customer.So we can not afford to overwrite any field information because at any time old information can be asked by management/regulator.

If every time for each field updation a new record is updated then customer master datawarehouse table would become 5 times if each customer record is updated five times during the year.

Suggest us the efficient approach to handle changing dimensions.

Thanks & Regards,

Sameer Gautam

Hi,

You don't have to create a record each time a change happens, just depends if you want to capture the history for that field or not. For example you may want to capture history for change of address, so you would add a new record, but you may not want it for surname, so just update all records for that customer with the new surname.

SCD are a pain to say the least when data warehousing, the principle is nice but coding it is sometimes complicated especially if you try and use snowflakes. And space soon becomes an issue, if you data changes regually. And you are right that if you make a change to a customer 5 times in a year then you will get 5 new records. Although you may code it so it only captures the end of year snapshot, rather than every change.

I would have a look through some of kimballs articles:

http://kimballgroup.com/html/articlesArchitecture/articlesAdvancedDim.html

Good luck

Matt

sql

Tuesday, March 20, 2012

Best Practice: Primary key in joing table

hi there,

i have the following joining table (many-to-many relationship)...

CREATE TABLE [dbo].[products_to_products_swatch] (
[products_to_products_swatch_id] [int] IDENTITY (1, 1) NOT FOR REPLICATION NOT NULL ,
[product_id] [int] NOT NULL ,
[products_swatch_id] [int] NOT NULL
) ON [PRIMARY]
GO

question: do i need to include a primary key in this table - being that it is a joing table?

thanks
mikejoing table ? i mean joining table :o)|||If this is simply implementing a many-to-many join, then there is no need for a surrogate key. Just declare a composite primary key consisting of the foreign keys to both tables.
If you are storing additional information regarding the relationship (timestamp, notes, modifier, whatever) you may want to include a surrogate key for developmental consistency with your other tables, but it is not required.

Monday, March 19, 2012

best practice question: JOIN criteria vs. WHERE criteria

For example, consider the following queries:


DECLARE @.SomeParam INT
SET @.SomeParam = 44

SELECT *
FROM TableA A
JOIN TableB B ON A.PrimaryKeyID = B.ForeignKeyID
WHERE B.SomeParamColumn = @.SomeParam

SELECT *
FROM TableA A
JOIN TableB B ON A.PrimaryKeyID = B.ForeignKeyID AND B.SomeParamColumn = @.SomeParam

Both of these queries return the same result set, but the first query filters the results in the WHERE clause whereas the the second query filters the results in the JOIN criteria. Once upon a time a DBA told me that I should always use the syntax of the first query (WHERE clause). Is there any truth to this, and if so, why?

Thanks.I checked the estimated execution plan and they were identical when i used a hard coded value instead of a parameter (@.someparam)

however,

when I used a parameter there was suddenly an execution difference.

The second query stored data in a temporary table. Thats something you'd definately want to avoid if you could. It also mis-guessed at the estimated row count.|||What tool did you use to check the execution plans? I checked it out with MS SQL Query Analyzer and saw no differences in execution plan when using a variable. Do you have example sql?

Thanks for the help!|||Always check the plan. And remember the plan *will* change as the stats for the table change. So make sure you've got a representative set of data.

Thursday, March 8, 2012

Best practice advice for efficient SQL connection code

Hi,

I have an application which is similar to the following example

Private Sub Start()
For a as int16 = 1 to 300
lstResults.items.add(GetPriceFromItem(a))
Next
End Sub

Private Function GetPriceFromItem(byval item as int16) as String
'Connect to SQL
'Execute "SELECT Price FROM Table WHERE Item='" & item.tostring & "'"
'Close Database connection
'Return Price
End Function

I want to know if there is a more efficeint way of doing this, i.e. i'm concerned that the routine creates 300 SqlConnection instances, 300 open/closes and 300 queries

Would a better way be to connect to SQL once, get the entire table then do the 300 "lookups" locally somehow, perhaps put it all into a DataTable, but can you query a datatable in this way, or could you suggest another control.

Best Regards

Ben


You might try one SQL statement which returns all of your needed records in one resultset, with a query like this:
SELECT Price, Item FROM Table WHERE Item BETWEEN 1 AND 300
(I suggest changing the data type of your Item column to integer.)|||

If lstResults is a listbox, then I would use tmorton's SELECT statement with a SqlDataSource control to fill the listbox instead of coding it. Unless of course, you want all of the items, then just don't put anything in the WHERE clause at all.

if lstResults is just a list, then use tmorton's SELECT statement with a datareader to fill the list all at once.

|||

Hi,

I just used lstResults to simplyfy my example, in the actual application these queries form part actually a DataTable which is built on the fly.

Most of the columns are populated with values coming from the Ebay API, then for the last column I take the value of column 0 which is ItemID and lookup to a SQL DB (approx 300 records)

Then datatable is bounded to a datagridview

|||

In that case, use the datareader and tmorton's SELECT statement, but you will need to reverse your logic. Read each record from the SQL Database, then find the row in the datatable that it corresponds to (if any).

Or, you can use a datareader, and stuff the result into a collection/dictionary, then iterate through the datatable, and use the itemID to retrieve the value from the collection/dictionary.

|||

Hi, yes thats the idea that I had. But what is a collection/dictionary?

|||

dim x as new collection

x.add("value1","key1")

x.add("value2","key2")

x.add("MyValue","Mykey")

debug.print x("key1") -- prints value1
debug.print x("Mykey") -- prints MyValue
debug.print x("key2") -- prints value2

A collection/dictionary is basically a key/value pair that allows you to store the value into an object and then quickly retrieve the value based on the key. Most implementations use a hashed key AND/OR binary tree structure so that retrieving the value is pretty fast, much faster than say iterating through an array looking for a key. Just be careful when you retrieve values from the collection as the default collection requires a string key. If you ask for a numeric key, then it'll act more like an array and give you back the nth entry in the collection rather than the value of that key.
So...
debug.print x(1) -- will retrieve the first value
debug.print x(cstr(1)) -- will retrieve the value that has a key of "1"

A dictionary is very similiar, as it stores and retrieves keys and values. In .NET dictionaries are a generic form of collection as far as I know, but with a few different methods, so the following will still work:
dim x as new generic.dictionary(Of string,string)
x.add("value","key")
debug.print x("key")

But you can't retrieve things by index like you can in a collection, so the following will NOT work:
debug.print x(1)

I think dictionaries are a bit faster than collections too.

|||

Hi

You could process just one sql statement (much more efficient use of the query engine) by using the IN statement eg.

select * from table

where tablefield IN ("a", "b", "c")

Hope this helps

Chris Seary

Best Practice & Other

Hi All
I have the following replication setup:
Replication Type: Transactional
Database Size: Circa 35gb
Articles: All articles are published and are required to be at the
subscriber.
Server1: Publisher, SQL 2000 Sp3 (W2k3 sp1)
Server2: Distributor, SQL 2000 Sp4 (W2k3 R2 sp1)
Server3: Subscriber SQL 2000 Sp3 (W2k3 sp1)
Server 3 has the pull subscription.
Other Info: Server 2 did have SQL2005 installed. It's since been
uninstalled and resolved some transactional issues.
This is the environment that I have inherited.
Based on reading around, this appears to be an acceptable best
practice method. I might press against throwing SP4 on server 1 and
server 3.
Are there any amazing troubleshooting tips for this process around?
there are times when the transactional replication does not work. I
think it times out so I'm looking at changing the time out to 3000
seconds.
One issue I've found is that there was a duplicated transaction that
managed to get through. This crashed the envrionment and there was no
choice but to create a new snapshot - it takes hours. How could we
best avoid this? If we deleted these transactions from the subscriber
(difficult due to referential integrity) how would the system know to
replicate them again?
Another one that we've had is where the old transactions are held in
the log. I need to flush them out so that the log can be truncated and
then reduced in size. Any further hints and tips?
I'm simply after some good practice methods to help troubleshoot and
plan the replication process since we're investing time and resource
in it rather heavily. We'll move to 2005 once things are stable.
Thanks in advance for the help.
Simon
Hi Paul
Thanks for the advice. Can you think of any really good
troubleshooting methods when things are gone wrong. I don't mind how
generic they are, it's just good to excercise the brain on new ways of
handling problems.
Cheers
Simon

Wednesday, March 7, 2012

Best Performance Query

Hi:

I have the following query, can somebody help me?

SELECT
s.Id, s.Name
FROM
Switch s
INNER JOIN
SwitchTelephoneRange r ON s.Id = r.Id
WHERE
'1526858' BETWEEN FromTelephone AND ToTelephone

Where the '1526858' is a phone number.

My problem is, I want to run the above query for each record in :

select Telephone from PhoneDirectory

So, each telephone number in the second phone, would macth the ' ' in the first query.

How can I do so? Do I need a loop? a cursor? Can you help please?

Thanks

Sounds like you need a correlated sub-query. Seehere andhere for more help.|||

Maybe something like this?

SELECT
s.Id, s.Name
FROM
Switch s
INNER JOIN
SwitchTelephoneRange r ON s.Id = r.Id
INNER JOIN
PhoneDirectory pd ON pd.Telephone BETWEEN FromTelephone AND ToTelephone

|||You could prob' do it by self joining too|||

Thanks for all.

Darek, your way is the best.

How can I join on a table without specifying that a key = key ?

You just joined on a table to get the phone number from and said

"inner join ... ON telephon between"

Can you explain that to me please?

That was a great tip.

Thanks a lot.

|||

Thanks.

Everything afterON inJOIN clause is nothing more like simply conditions.

You can write something like that:

FROM a
inner join b.SomeVarChar LIKE a.SomeOtherVarChar

Previous query in ther way:

SELECT
s.Id, s.Name
FROM
Switch s
INNER JOIN
SwitchTelephoneRange r
INNER JOIN
PhoneDirectory pd
WHERE
s.Id = r.Id
AND pd.Telephone BETWEEN FromTelephone AND ToTelephone

Best method for maintaining list?

Hi All,
I am wondering what, if any, method would best suit the following request.
I want to maintain a list of items in SQL Server.
I'm thinking a Stored Procedure.
The list is of two columns: (both VarChar)
colName, colTag
data:
Name1, Tag1
Name2, Tag2
Name3, Tag3
Name5, Tag4
Now, before anyone says, why not a table, I would answer that I want to be
able to add/move line items around easily. And I don't want to have to
renumber an ID column of any type.
So If I wanted to quickly add a new row to this data between Name2 and
Name3, I don't want to have to open up Enterprise explorer to do it.
This list is for pulling into a .NET application.
Any ideas would be great.
Thanks,
John.You could create a stored procedure and return the values as shown below
SELECT 'Name1' as NameField,'Tag1' as TagField
UNION ALL
SELECT 'Name2' as NameField,'Tag2' as TagField
UNION ALL
SELECT 'Name3' as NameField,'Tag3' as TagField
UNION ALL
SELECT 'Name4' as NameField,'Tag4' as TagField
UNION ALL
SELECT 'Name1' as NameField,'Tag5' as TagField
"John" wrote:

> Hi All,
> I am wondering what, if any, method would best suit the following request.
> I want to maintain a list of items in SQL Server.
> I'm thinking a Stored Procedure.
> The list is of two columns: (both VarChar)
> colName, colTag
> data:
> Name1, Tag1
> Name2, Tag2
> Name3, Tag3
> Name5, Tag4
> Now, before anyone says, why not a table, I would answer that I want to be
> able to add/move line items around easily. And I don't want to have to
> renumber an ID column of any type.
> So If I wanted to quickly add a new row to this data between Name2 and
> Name3, I don't want to have to open up Enterprise explorer to do it.
> This list is for pulling into a .NET application.
> Any ideas would be great.
> Thanks,
> John.
>
>|||>> I want to maintain a list of items in SQL Server. <<
SQL has no list structure. It also has no pointers with which to
create such a thing.
Why did you put that silly, redundant prefix on the column names?
People who know RDBMS, data modeling and ISO-11179 Standards do not do
this!
Since the table is the ONLY data structure in SQL, you either need to
model your problem in SQL or you need to use LISP or some other
language that has list structures.
But you do not mind the prospect of the pointer chains in list
manipulations? Which also leads to the quesitions, where the DDL? And
what is the key?
You might want to look up the "Information Principle" when you finally
study RDBMS. All information is represented as values in columns --
NOT by something physical in the storage.
Rows are not records; fields are not columns; tables are not files;
there is no sequential access or ordering in an RDBMS, so "first",
"next" and "last" are totally meaningless. If you want an ordering,
then you need to have a column that defines that ordering.
Why are trying to design the database to fit an application? That is
what we did 40+ yers ago when we had file systems and procedural
languages, not RDBMS and tiered architectures.
Given a table with an ordering column, position, like this:
CREATE TABLE Foobar
(display_position INTEGER NOT NULL PRIMARY KEY
CHECK (display_position > 0),
foo_value CHAR(10) NOT NULL);
Re-arrange the display order of foo_value based on the position column:
CREATE PROCEDURE SwapFoobars (@.old_position INTEGER, @.new_position
INTEGER)
AS
UPDATE Foobar
SET display_position
= CASE display_position
WHEN @.old_position
THEN @.new_position
ELSE display_position + SIGN(@.old_position - @.new_pos)
END
WHERE display_position BETWEEN @.old_position AND @.new_position
OR display_position BETWEEN @.new_position AND @.old_position;
When you want to drop a few rows, remember to close the gaps with this:
CREATE PROCEDURE CloseFoobarGaps ()
AS
UPDATE Foobar
SET display_position
= (SELECT COUNT (F1.position)
FROM Foobar AS F1
WHERE F1.display_position <= Foobar.display_position);
Is this so hard?|||If the data is persistant the generally, the best approach is to use a
table.
If you bought into the idea of hardcoding the values in a stored procedure,
you will have to deal with other issues -- not only you cannot alter them
without some convoluted logic, but adding and deleting items to the list
would amount to re-writing the procedure everytime.
Anith|||> Why are trying to design the database to fit an application? That is
> what we did 40+ yers ago when we had file systems and procedural
> languages, not RDBMS and tiered architectures.
You where coding using file systems in the mid/late 60's?
Interesting, they weren't even in manufacture by then, file systems where
only introduced in the mid/late 70's.
90% of the rest of your post is just crap and twoddle I won't even bother
commenting on.
Tony Rogerson
SQL Server MVP
http://sqlblogcasts.com/blogs/tonyrogerson - technical commentary from a SQL
Server Consultant
http://sqlserverfaq.com - free video tutorials
"--CELKO--" <jcelko212@.earthlink.net> wrote in message
news:1149526125.455976.101630@.g10g2000cwb.googlegroups.com...
> SQL has no list structure. It also has no pointers with which to
> create such a thing.
>
> Why did you put that silly, redundant prefix on the column names?
> People who know RDBMS, data modeling and ISO-11179 Standards do not do
> this!
>
> Since the table is the ONLY data structure in SQL, you either need to
> model your problem in SQL or you need to use LISP or some other
> language that has list structures.
>
> But you do not mind the prospect of the pointer chains in list
> manipulations? Which also leads to the quesitions, where the DDL? And
> what is the key?
>
> You might want to look up the "Information Principle" when you finally
> study RDBMS. All information is represented as values in columns --
> NOT by something physical in the storage.
> Rows are not records; fields are not columns; tables are not files;
> there is no sequential access or ordering in an RDBMS, so "first",
> "next" and "last" are totally meaningless. If you want an ordering,
> then you need to have a column that defines that ordering.
>
> Why are trying to design the database to fit an application? That is
> what we did 40+ yers ago when we had file systems and procedural
> languages, not RDBMS and tiered architectures.
> Given a table with an ordering column, position, like this:
> CREATE TABLE Foobar
> (display_position INTEGER NOT NULL PRIMARY KEY
> CHECK (display_position > 0),
> foo_value CHAR(10) NOT NULL);
> Re-arrange the display order of foo_value based on the position column:
>
> CREATE PROCEDURE SwapFoobars (@.old_position INTEGER, @.new_position
> INTEGER)
> AS
> UPDATE Foobar
> SET display_position
> = CASE display_position
> WHEN @.old_position
> THEN @.new_position
> ELSE display_position + SIGN(@.old_position - @.new_pos)
> END
> WHERE display_position BETWEEN @.old_position AND @.new_position
> OR display_position BETWEEN @.new_position AND @.old_position;
> When you want to drop a few rows, remember to close the gaps with this:
> CREATE PROCEDURE CloseFoobarGaps ()
> AS
> UPDATE Foobar
> SET display_position
> = (SELECT COUNT (F1.position)
> FROM Foobar AS F1
> WHERE F1.display_position <= Foobar.display_position);
> Is this so hard?
>|||Yup, that is what I was thinking too.
As it stands I create the actual list on the client side's objects.
I was just wondering if there was a mechanism on the SQL side of things that
I did not know about. If there was it would save me time if I needed to
append the listing, I could do it on the server.
Thanks for you help,
John.
"Anith Sen" <anith@.bizdatasolutions.com> wrote in message
news:OJjO0BMiGHA.3296@.TK2MSFTNGP05.phx.gbl...
> If the data is persistant the generally, the best approach is to use a
> table.
> If you bought into the idea of hardcoding the values in a stored
> procedure, you will have to deal with other issues -- not only you cannot
> alter them without some convoluted logic, but adding and deleting items to
> the list would amount to re-writing the procedure everytime.
> --
> Anith
>|||>> You were coding using file systems in the mid/late 60's? Interesting, th
ey weren't even in manufacture by then, file systems where only introduced i
n the mid/late 70's. <<
Why do you think that computers before 1960 had no files? That is
stilly.
When do you think that magnetic tapes and punch cards (aka "Unit Record
Equipment") were invented? Those tapes were the only thing we had in
the dark ages. Hard drives were insanely costly and were used for
sorting space and not data storage at first. .
Disk based systems came latter and were cheap enough in the mid-1970's
to be on mini-computers. The first DBMS I used was IMAGE/3000, whcih
was a version of TOTAL.|||> Why do you think that computers before 1960 had no files? That is
> stilly.
> When do you think that magnetic tapes and punch cards (aka "Unit Record
> Equipment") were invented? Those tapes were the only thing we had in
> the dark ages. Hard drives were insanely costly and were used for
> sorting space and not data storage at first. .
> Disk based systems came latter and were cheap enough in the mid-1970's
> to be on mini-computers. The first DBMS I used was IMAGE/3000, whcih
> was a version of TOTAL.
>
Tapes do not have "file systems" - a very big leap from a "file" which is a
unit of data, tapes have headers which contain amongst other things a data
marker.
Tapes only have a flat directory structure, they have no concept of
hierarchy organisation.
You probably need to read: http://en.wikipedia.org/wiki/File_system.

> the dark ages. Hard drives were insanely costly and were used for
> sorting space and not data storage at first. .
.... and where not available until early mid 70's or can you provide a lin
k
to disprove me?
According to your 'class of 65' you certainly weren't even in IT in the
early 60's and where only just leaving school!
http://www.baker.hs.org/65/celko-joe.html
Tony Rogerson
SQL Server MVP
http://sqlblogcasts.com/blogs/tonyrogerson - technical commentary from a SQL
Server Consultant
http://sqlserverfaq.com - free video tutorials
"--CELKO--" <jcelko212@.earthlink.net> wrote in message
news:1149971774.904725.271250@.h76g2000cwa.googlegroups.com...
> Why do you think that computers before 1960 had no files? That is
> stilly.
> When do you think that magnetic tapes and punch cards (aka "Unit Record
> Equipment") were invented? Those tapes were the only thing we had in
> the dark ages. Hard drives were insanely costly and were used for
> sorting space and not data storage at first. .
> Disk based systems came latter and were cheap enough in the mid-1970's
> to be on mini-computers. The first DBMS I used was IMAGE/3000, whcih
> was a version of TOTAL.
>

Saturday, February 25, 2012

Best data base design

Hi all,
Can any one of you help me out in giving the ideal database design for the following requirement.
I will be having two heirachy of data. One which can be accesed by the master user and others by clients. There can be n number of clients who can be there. A client can view only his details and the masters.
A master can view data of all the clients and the master. Each clients detail is expected to be kept in a different table.

So in an apllication if the person who logs in is a master user we need to show details of all clients.
If the person logs in as a client A then details of only his table is to be shown.
Can any one get back on this,
Thanking you in advance
VyasFor what its worth ...

I would only use Views to allow them to see the data, and stored procedures to update.

For viewing data, I would create an association table with logins and allowed entities

create table SecurityControl
(
securitycontrol_id int identity not null ,
user varchar(40) not null,
company_no int not null
)


then in the views i would join to it like so:

select
ci.*
from CompanyInfo ci
join SecurityControl si on si.company_no = ci.company_no and suser_name() = si.user


SQL 2000 does have row level security capability but
1. I haven't used it enough to explain it.
2. You didn't specific a version and this solution would be portable to most RDBMS's

Monday, February 13, 2012

Beginner: How to group data?

Hello,
Thanks for reviewing my question. I am new to reporting services and
experimented with a couple of reports. I have the following data in a table:
# name slot
1 A1 1
1 B1 2
1 C1 3
2 A2 1
2 B2 2
2 C2 3
I would like to output in this fashison:
1 2
-- --
1 A1 A2
2 B1 B2
3 C1 C2
Should I be looking to use a Matrix objecjt? Do I need to use JOINs to
group rows/columns even though all my data I need is in my table?
Many Thanks
PeterA follow up:
I am not familar with how the reporting mechanism groups the data. I have a
long list of data already contained in a table.
Current list
1 Book A Action
1 Book B Drama
2 Book C Novel
2 Book D Action
Desired output
1 2
Action Book A Book D
Drama Book B
Novel Book C
Can I output the data in the desired output or do I have to do queries with
cross joins or something of that sort?
Many Thanks
Peter
"Peter" wrote:
> Hello,
> Thanks for reviewing my question. I am new to reporting services and
> experimented with a couple of reports. I have the following data in a table:
> # name slot
> 1 A1 1
> 1 B1 2
> 1 C1 3
> 2 A2 1
> 2 B2 2
> 2 C2 3
> I would like to output in this fashison:
> 1 2
> -- --
> 1 A1 A2
> 2 B1 B2
> 3 C1 C2
> Should I be looking to use a Matrix objecjt? Do I need to use JOINs to
> group rows/columns even though all my data I need is in my table?
> Many Thanks
> Peter
>

Beginner T-SQL Question

I'd like to query my Tasks and TaskActivity Tables to return the following results:

Case Id
Estimated Hours
Total Hours
Remaining Hours

Because I'm an SQL novice, I've had to resort to a hack of creating three different views to get the results I want: I'm sure there's a better way (i.e. a single, well-formed query) but when I try that my numbers are all wrong.

Here's my hack to get the correct results:

First I have a view to get my Estimated Hours and CaseId from my TASKS table:
SELECT COALESCE (SUM(EstHrs), 0.00) AS EstHrs, CaseId
FROM dbo.Tasks
GROUP BY CaseId

Then I have a view to get my Total Hours and CaseId from my TASKACTIVITES table:
SELECT Tasks.CaseId, SUM(TaskActivity.Minutes / 60.00) AS TotalHrs
FROM TaskActivity RIGHT OUTER JOIN
Tasks ON TaskActivity.TaskId = Tasks.TaskId
GROUP BY Tasks.CaseId

Finally I have a third view (that I actually use in my program) to put it all together:
SELECT vTaskActual.CaseId, vTaskEstimates.EstHrs, vTaskActual.TotalHrs,
vTaskActual.TotalHrs - vTaskEstimates.EstHrs AS RemHrs
FROM vTaskActual INNER JOIN
vTaskEstimates ON vTaskActual.CaseId = vTaskEstimates.CaseId

Any help would be greatly appreciated, and, if this is not the correct forum for newbie questions like this, please let me know.

TIA,
Rob

You can turn a query containing a single select statement into a derived table by surround it in parethesises and adding an alias. eg

select managers.name, managers.SSN, dept.departmentCode, dept.description

from department as dept

join (select name, SSN, deptid from employee where salary > 50.000) as managers

on dept.deptid = managers.deptid

So with the two views above, turn both into derived tables, and join:

select TaskActual.CaseId, TaskEstimates.EstHrs, TaskActual.TotalHrs,
TaskActual.TotalHrs - TaskEstimates.EstHrs AS RemHrs

from

(SELECT Tasks.CaseId, SUM(TaskActivity.Minutes / 60.00) AS TotalHrs
FROM TaskActivity RIGHT OUTER JOIN
Tasks ON TaskActivity.TaskId = Tasks.TaskId
GROUP BY Tasks.CaseId
) as TaskEstimates

INNER JOIN

(SELECT Tasks.CaseId, SUM(TaskActivity.Minutes / 60.00) AS TotalHrs
FROM TaskActivity RIGHT OUTER JOIN
Tasks ON TaskActivity.TaskId = Tasks.TaskId
GROUP BY Tasks.CaseId) as TaskActual

ON TaskActual.CaseId = TaskEstimates.CaseId

That should do it. As both derived table queries use the tasks table, it is likely that you can do the query in one query without using derived tables, but without having a better understanding of your schema and data I don't want to attempt that!

HTH

For more SQl tips, check out my blog:

|||Please indicate if this answered your question or not.|||

Thanks for the reply it was very helpful.

I did have to make a few changes to your response (see below) because my results are gathered from two different tables: Tasks contains the estimate, and TaskActivity contains the records of actual time. The info on derived tables will really help clean-up my DB.

Thanks again!

P.S. I use "COALESCE" to assign 0.00 to any NULL values in EstHrs. It is working so I assume that is correct)

Here's the final query that's working:

select TaskActual.CaseId, TaskEstimates.EstHrs, TaskActual.TotalHrs,

TaskActual.TotalHrs - TaskEstimates.EstHrs AS RemHrs

from

(SELECT COALESCE (SUM(EstHrs), 0.00) AS EstHrs, CaseId

FROM dbo.Tasks

GROUP BY CaseId

) as TaskEstimates

INNER JOIN

(SELECT dbo.Tasks.CaseId, SUM(dbo.TaskActivity.Minutes / 60.00) AS TotalHrs

FROM dbo.TaskActivity RIGHT OUTER JOIN

dbo.Tasks ON dbo.TaskActivity.TaskId = dbo.Tasks.TaskId

GROUP BY dbo.Tasks.CaseId) as TaskActual

ON TaskActual.CaseId = TaskEstimates.CaseId

Beginner prob: generating string

Help!

I'm new to T-SQL and trying to code a solve for the following problem, without a good idea of how I can make T-SQL jump through hoops. Here is the problem.

I need to populate a single string with values from a series of possible fields.

eg. a vehicle can be 4 wheel drive (4WD) and have air conditioning (Aircon).

So for each stock record I want to test each of a range of values (all or none can be true) in a column for a match. Based on that, add to the output string (that would look like "4wd ac ab abs").

So far I have :

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

CREATE proc [dbo].[qry_EXPERIMENT_02-12-2003]

--provides information for the 'notes' field of the results screen.
--default value: NULL
@.notesString nvarchar (30) = NULL

as

SELECT
tblStockExtra.StockID,

(
SELECT
CASE WHEN tblExtra.ExtraHeader = '4WD' THEN '4WD ' END,
CASE WHEN tblExtra.ExtraHeader = 'Aachk' THEN 'aa ' END,
CASE WHEN tblExtra.ExtraHeader = 'Aircon' OR tblExtra.ExtraHeader = 'DualAircon' OR tblExtra.ExtraHeader = 'ClimateAirCon' THEN 'ac ' END,
CASE WHEN tblExtra.ExtraHeader = 'ABS' THEN 'abs ' END,
CASE WHEN tblExtra.ExtraHeader = 'AlloyWheel' OR tblExtra.ExtraHeader = 'FactoryAlloyWheel ' THEN 'aw ' END,
CASE WHEN tblExtra.ExtraHeader = 'SRSAirBag' OR tblExtra.ExtraHeader = 'DualSRSAirBag' THEN 'ab ' END,
CASE WHEN tblExtra.ExtraHeader = 'CD' OR tblExtra.ExtraHeader = 'CDShuttle' THEN 'cd ' END

FROM tblExtra
INNER JOIN tblStockExtra ON tblExtra.ExtraID = tblStockExtra.ExtraID
INNER JOIN tblStock ON tblStockExtra.StockID = tblStock.StockID
) AS notes

FROM tblStockExtra, tblExtra

GROUP BY tblStockExtra.StockID, tblExtra.Extraheader

ORDER BY tblStockExtra.StockID

This doesn't work, as I assume a subquery can only return 1 value. I'm hoping someone knowledgable can see what I'm attempting to do and enlighten me!

Do I need to be using Dynamic SQL?

Many thanks for your thoughts and time,

KC.You are right, this will not work. It would be easier for us if you post :

a) table descriptions of tblStock, tblExtra, tblStockExtra
b) the foreign keys between those tables (that way we can have an idea about the relationships between them)
c) some sample data
d) an example of how you would like to output to be formatted|||Originally posted by cvandemaele
You are right, this will not work. It would be easier for us if you post :

a) table descriptions of tblStock, tblExtra, tblStockExtra
b) the foreign keys between those tables (that way we can have an idea about the relationships between them)
c) some sample data
d) an example of how you would like to output to be formatted

A) Many to many realtionship between tblStock and tblExtra with tblStockExtra as a bridging table
B) Referential integrity not enforced (Don't ask! Its not mine :) )
C)

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tblExtra]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[tblExtra]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tblStock]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[tblStock]
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[tblStockExtra]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[tblStockExtra]
GO

CREATE TABLE [dbo].[tblExtra] (
[ExtraID] [int] NOT NULL ,
[ExtraDesc] [nvarchar] (255) NULL ,
[ExtraAbbrv] [nvarchar] (255) NULL ,
[ExtraHeader] [nvarchar] (50) NULL ,
[Group] [int] NULL
) ON [PRIMARY]
GO

CREATE TABLE [dbo].[tblStock] (
[StockID] [int] NOT NULL ,
) ON [PRIMARY]
GO

CREATE TABLE [dbo].[tblStockExtra] (
[StockExtraID] [int] IDENTITY (1, 1) NOT NULL ,
[StockID] [int] NULL ,
[ExtraID] [int] NULL
) ON [PRIMARY]
SET IDENTITY_INSERT [dbo].[tblStockExtra] ON
GO

ALTER TABLE [dbo].[tblStockExtra] WITH NOCHECK ADD
CONSTRAINT [PK_tblStockExtra] PRIMARY KEY NONCLUSTERED
(
[StockExtraID]
) ON [PRIMARY]
GO

INSERT INTO tblStock
(StockID)
VALUES (64);
INSERT
INTO tblStock(StockID)
VALUES (65);
INSERT
INTO tblStock(StockID)
VALUES (467);
INSERT
INTO tblStock(StockID)
VALUES (487);
INSERT
INTO tblStock(StockID)
VALUES (944);

--4wd
INSERT INTO tblExtra
(ExtraID, ExtraDesc, ExtraAbbrv, ExtraHeader, [Group])
VALUES (41,'4 wheel drive', '4WD', '4WD', 14)

--aachk
INSERT INTO tblExtra
(ExtraID, ExtraDesc, ExtraAbbrv, ExtraHeader, [Group])
VALUES (52, 'AA check', 'AA', 'Aachk', 17)

--aircon
INSERT INTO tblExtra
(ExtraID, ExtraDesc, ExtraAbbrv, ExtraHeader, [Group])
VALUES (8, 'air-conditioning', 'AC', 'AirCon', 2)
INSERT INTO tblExtra
(ExtraID, ExtraDesc, ExtraAbbrv, ExtraHeader, [Group])
VALUES (9, 'climate air-conditioning', 'AAC', 'ClimateAirCon', 2)
INSERT INTO tblExtra
(ExtraID, ExtraDesc, ExtraAbbrv, ExtraHeader, [Group])
VALUES (10, 'dual air condtioning', 'DAC', 'DualAirCon', 2)

--abs
INSERT INTO tblExtra
(ExtraID, ExtraDesc, ExtraAbbrv, ExtraHeader, [Group])
VALUES (39, 'antilock braking system', 'ABS', 'ABS', 12)

--alloys
INSERT INTO tblExtra
(ExtraID, ExtraDesc, ExtraAbbrv, ExtraHeader, [Group])
VALUES (27, 'alloy wheels', 'AW', 'AlloyWheel', 9)
INSERT INTO tblExtra
(ExtraID, ExtraDesc, ExtraAbbrv, ExtraHeader, [Group])
VALUES (28, 'factory alloy wheels', 'FAW', 'FactoryAlloyWheel', 9)

--airbags
INSERT INTO tblExtra
(ExtraID, ExtraDesc, ExtraAbbrv, ExtraHeader, [Group])
VALUES (25, 'SRS airbag', 'AB', 'SRSAirBag', 8)
INSERT INTO tblExtra
(ExtraID, ExtraDesc, ExtraAbbrv, ExtraHeader, [Group])
VALUES (26, 'dual SRS airbag', 'DAB', 'DualSRSAirBag', 8)

--CD
INSERT INTO tblExtra
(ExtraID, ExtraDesc, ExtraAbbrv, ExtraHeader, [Group])
VALUES (13, 'CD', 'CD', 'CD', 3)
INSERT INTO tblExtra
(ExtraID, ExtraDesc, ExtraAbbrv, ExtraHeader, [Group])
VALUES (14, 'CD shuttle', 'CDS', 'CDShuttle', 3)

INSERT INTO tblStockExtra
(StockExtraID, StockID, ExtraID)
VALUES (1112,64,8)
INSERT INTO tblStockExtra
(StockExtraID, StockID, ExtraID)
VALUES (1113,64,12)
INSERT INTO tblStockExtra
(StockExtraID, StockID, ExtraID)
VALUES (1115,64,23)
INSERT INTO tblStockExtra
(StockExtraID, StockID, ExtraID)
VALUES (1116,64,15)
INSERT INTO tblStockExtra
(StockExtraID, StockID, ExtraID)
VALUES (1117,64,60)
INSERT INTO tblStockExtra
(StockExtraID, StockID, ExtraID)
VALUES (1118,64,7)
INSERT INTO tblStockExtra
(StockExtraID, StockID, ExtraID)
VALUES (1118,64,59)
INSERT INTO tblStockExtra
(StockExtraID, StockID, ExtraID)
VALUES (1119,65,8)
INSERT INTO tblStockExtra
(StockExtraID, StockID, ExtraID)
VALUES (1120,65,39)
INSERT INTO tblStockExtra
(StockExtraID, StockID, ExtraID)
VALUES (1121,65,14)
INSERT INTO tblStockExtra
(StockExtraID, StockID, ExtraID)
VALUES (1122,65,23)
INSERT INTO tblStockExtra
(StockExtraID, StockID, ExtraID)
VALUES (1123,65,26)
INSERT INTO tblStockExtra
(StockExtraID, StockID, ExtraID)
VALUES (1124,65,16)
INSERT INTO tblStockExtra
(StockExtraID, StockID, ExtraID)
VALUES (1125,65,15)
INSERT INTO tblStockExtra
(StockExtraID, StockID, ExtraID)
VALUES (1126,65,43)
INSERT INTO tblStockExtra
(StockExtraID, StockID, ExtraID)
VALUES (1127,65,7)
INSERT INTO tblStockExtra
(StockExtraID, StockID, ExtraID)
VALUES (1128,65,12)
INSERT INTO tblStockExtra
(StockExtraID, StockID, ExtraID)
VALUES (4357,467,7)
INSERT INTO tblStockExtra
(StockExtraID, StockID, ExtraID)
VALUES (4358,467,8)
INSERT INTO tblStockExtra
(StockExtraID, StockID, ExtraID)
VALUES (4359,467,11)
INSERT INTO tblStockExtra
(StockExtraID, StockID, ExtraID)
VALUES (4465,487,7)
INSERT INTO tblStockExtra
(StockExtraID, StockID, ExtraID)
VALUES (4466,487,8)
INSERT INTO tblStockExtra
(StockExtraID, StockID, ExtraID)
VALUES (4467,487,11)
INSERT INTO tblStockExtra
(StockExtraID, StockID, ExtraID)
VALUES (4468,487,67)
INSERT INTO tblStockExtra
(StockExtraID, StockID, ExtraID)
VALUES (9188,944,7)
INSERT INTO tblStockExtra
(StockExtraID, StockID, ExtraID)
VALUES (9189,944,8)
INSERT INTO tblStockExtra
(StockExtraID, StockID, ExtraID)
VALUES (9190,944,12)
INSERT INTO tblStockExtra
(StockExtraID, StockID, ExtraID)
VALUES (9191,944,16)
INSERT INTO tblStockExtra
(StockExtraID, StockID, ExtraID)
VALUES (9192,944,15)
INSERT INTO tblStockExtra
(StockExtraID, StockID, ExtraID)
VALUES (9193,944,20)
INSERT INTO tblStockExtra
(StockExtraID, StockID, ExtraID)
VALUES (9194,944,23)
INSERT INTO tblStockExtra
(StockExtraID, StockID, ExtraID)
VALUES (9195,944,28)
INSERT INTO tblStockExtra
(StockExtraID, StockID, ExtraID)
VALUES (9196,944,64)
INSERT INTO tblStockExtra
(StockExtraID, StockID, ExtraID)
VALUES (9197,944,41)

D) I want the output as: "Extra1 Extra2 Extra3"

Thanks for your help!

KC.|||As the list of extras linked to an item in StockId is unlimited, the list of extras is returned as a large string, seperated by a single character.

First of all, create the following function

create function dbo.fGetOptionList (@.CarId int, @.Separator char(1))
returns nvarchar(510)
as
begin

-- cursor that will browse throught the list of extra for the given car
declare cOptionList
cursor for
select
options.extraabbrv as OptionAbbrv
from tblstock as cars
inner join tblstockextra as cars_options
on cars.stockid = cars_options.stockid
inner join tblextra as options
on options.extraid = cars_options.extraid
where Cars.stockid = @.CarId

declare @.OptionAbbrv nvarchar(510)
declare @.AllOptions nvarchar(510)

open cOptionList
fetch next from cOptionList into @.OptionAbbrv
while @.@.fetch_status = 0
begin
set @.AllOptions = rtrim(isnull(@.AllOptions,'')) + rtrim(isnull(@.OptionAbbrv,'')) + @.Separator
fetch next from cOptionList into @.OptionAbbrv
end
close cOptionList
deallocate cOptionList

return @.AllOptions

end

Afterwards, just :
SELECT
stockid,
dbo.fgetoptionlist(stockid, ';') as OptionList
FROM tblstock

It will return :
stockid OptionList
---- -----
64 AC;
65 AC;ABS;CDS;DAB;
467 AC;
487 AC;
944 AC;FAW;4WD;

(5 row(s) affected)|||Wow!

Thanks for your time and energy! I truly wasn't expecting the solution on a plate! Please accept my sincerest thanks, you've saved me a great deal of effort!

I feel disappointed I can't reward you with a commendation as in other forums, but you've made my day!

:) :) :)

KC.

Sunday, February 12, 2012

Beginner @IDENTITY question

Hello,
When I execute the following code on my localhost the INSERT statement is successfull and my ID is entered. But for some reason when I uploaded to my remote host the exact same database (MS SQL) and code it keeps trying to enter a NULL value into the ID column- which causes an error? I don't understand becuase it is the exact same app and database but at a remote location.

Is @.IDENTITY somehow saved in the session and my remote servers session settings?? are off?

strSql = "insert into Login (UserName,Password) VALUES ('" + UserName.Text.Trim() + "','" + Password.Text.Trim() + "') select @.ID = @.@.IDENTITY";

Thanks in advance for any responses.
-WileyHi Wiley,

First, you should have a ; between the statements:

strSql = "insert into Login (UserName,Password) VALUES ('" + UserName.Text.Trim() + "','" + Password.Text.Trim() + "'); select @.ID = @.@.IDENTITY";

Second, you should probably be using SCOPE_IDENTITY instead of @.@.IDENTITY. The two are similar, but SCOPE_IDENTITY returns values inserted only within the current scope. The problem with @.@.IDENTITY is that you might get the ID value from another insert operation. Check out SQL Server Books Online for a more complete description of the issue.

But that doesn't explain your problem. My best guess is that the ID field isn't defined as an identity field in the database on the remote server. That's the first thing to check.

There is a slight chance that SET IDENTITY_INSERT is off in the database. I don't recall that you can set that as the normal setting, but something in the connection might be setting it. Definitely a longshot.

Third,DON'T USE DYNAMIC SQL THIS WAY!!!!! It opens up SQL injection attacks, particularly for fields that are obviously user input. If you don't know the issues, just ask. You are setting yourself up to have your app hacked and attacked.

Don|||Hello,
Part of my problem was that I created the database locally from a .dat file in a database called Resume. Everthing worked great. When I upoaded the tables to my remote assigned database which is called "mydatabase" not Resume I ran into permission problems becuase locally the owner was dbo and remotely the owner was "mydatabase". Also some of the ID fields were not set to IDENTITY.

I basically have my application working(sort of ) now but I have to allow NULLS on every column that allows them in every table for anything to (sort of ) work -which I DID NOT have to do locally and I can't figure out why, maybe someone can shed some light on that for me.

Also, in reference to SQL injection attacks that you mentioned above , maybe you can point me to a link on ms sql security and explain to me what is wrong with using the dynamic sql statement in the way i did. I definitely don't want to start using asp.net and start off on the wrong foot opening myself up for attacks.

thanks,
-Wiley|||there's a lot of info about sql inject that you can find on the web. some of them are:

http://www.asp.net/Forums/ShowPost.aspx?tabindex=1&PostID=533341

http://www.spidynamics.com/papers/SQLInjectionWhitePaper.pdf

http://www.nextgenss.com/papers/advanced_sql_injection.pdf

http://www.nextgenss.com/papers/more_advanced_sql_injection.pdf

google rocks!|||wrong text on the first link. my mistake.

Friday, February 10, 2012

Begginer needing help to resolve error.

Hi,
I hope one of you may be able to help me with a small probelm I have.
I get the following error:
Microsoft JET Database Engine error '80040e14'
Syntax error (missing operator) in query expression '[Date_Completed]
is NULL WHERE (([Customer] LIKE '%Davie%' OR [Address] LIKE '%Davie%'
OR [Post_Code] LIKE '%Davie%' OR [Telephone] LIKE '%Davie%' OR
[Mobile] LIKE '%Davie%' OR [Vehicle] LIKE '%Davie%' OR [Chassis_No]
LIKE '%Davie%' OR [Engine_No] LIKE ''.
/Jobsheet/Datalist.asp, line 227
The code that it highlights is this:
<%
' Set up Record Set
Set rs = Server.CreateObject("ADODB.Recordset")
rs.CursorLocation = 3
rs.Open sSql, conn, 1, 2 --This line in particular --
nTotalRecs = rs.RecordCount
If nDisplayRecs <= 0 Then ' Display All Records
nDisplayRecs = nTotalRecs
End If
nStartRec = 1
SetUpStartRec() ' Set Up Start Record Position
%>
I would be much obliged if anyone can provide assistance.
Cheers,
PhillIs it Access query?
"FatboyDim" <webmaster@.pb-enterprises.co.uk> wrote in message
news:1183454575.272248.54230@.c77g2000hse.googlegroups.com...
> Hi,
> I hope one of you may be able to help me with a small probelm I have.
> I get the following error:
> Microsoft JET Database Engine error '80040e14'
> Syntax error (missing operator) in query expression '[Date_Completed]
> is NULL WHERE (([Customer] LIKE '%Davie%' OR [Address] LIKE '%Davie%'
> OR [Post_Code] LIKE '%Davie%' OR [Telephone] LIKE '%Davie%' OR
> [Mobile] LIKE '%Davie%' OR [Vehicle] LIKE '%Davie%' OR [Chassis_No]
> LIKE '%Davie%' OR [Engine_No] LIKE ''.
> /Jobsheet/Datalist.asp, line 227
>
> The code that it highlights is this:
> <%
> ' Set up Record Set
> Set rs = Server.CreateObject("ADODB.Recordset")
> rs.CursorLocation = 3
> rs.Open sSql, conn, 1, 2 --This line in particular --
> nTotalRecs = rs.RecordCount
> If nDisplayRecs <= 0 Then ' Display All Records
> nDisplayRecs = nTotalRecs
> End If
> nStartRec = 1
> SetUpStartRec() ' Set Up Start Record Position
> %>
> I would be much obliged if anyone can provide assistance.
> Cheers,
> Phill
>|||Yes,
It is an Access query.
On 3 Jul, 10:27, "Uri Dimant" <u...@.iscar.co.il> wrote:
> Is it Access query?
> "FatboyDim" <webmas...@.pb-enterprises.co.uk> wrote in message
> news:1183454575.272248.54230@.c77g2000hse.googlegroups.com...
>
> > Hi,
> > I hope one of you may be able to help me with a small probelm I have.
> > I get the following error:
> > Microsoft JET Database Engine error '80040e14'
> > Syntax error (missing operator) in query expression '[Date_Completed]
> > is NULL WHERE (([Customer] LIKE '%Davie%' OR [Address] LIKE '%Davie%'
> > OR [Post_Code] LIKE '%Davie%' OR [Telephone] LIKE '%Davie%' OR
> > [Mobile] LIKE '%Davie%' OR [Vehicle] LIKE '%Davie%' OR [Chassis_No]
> > LIKE '%Davie%' OR [Engine_No] LIKE ''.
> > /Jobsheet/Datalist.asp, line 227
> > The code that it highlights is this:
> > <%
> > ' Set up Record Set
> > Set rs = Server.CreateObject("ADODB.Recordset")
> > rs.CursorLocation = 3
> > rs.Open sSql, conn, 1, 2 --This line in particular --
> > nTotalRecs = rs.RecordCount
> > If nDisplayRecs <= 0 Then ' Display All Records
> > nDisplayRecs = nTotalRecs
> > End If
> > nStartRec = 1
> > SetUpStartRec() ' Set Up Start Record Position
> > %>
> > I would be much obliged if anyone can provide assistance.
> > Cheers,
> > Phill- Hide quoted text -
> - Show quoted text -|||Hi
Its SQL Server news group. You will be better of ask the question in Access
group
"FatboyDim" <webmaster@.pb-enterprises.co.uk> wrote in message
news:1183455450.654505.196030@.n2g2000hse.googlegroups.com...
> Yes,
> It is an Access query.
> On 3 Jul, 10:27, "Uri Dimant" <u...@.iscar.co.il> wrote:
>> Is it Access query?
>> "FatboyDim" <webmas...@.pb-enterprises.co.uk> wrote in message
>> news:1183454575.272248.54230@.c77g2000hse.googlegroups.com...
>>
>> > Hi,
>> > I hope one of you may be able to help me with a small probelm I have.
>> > I get the following error:
>> > Microsoft JET Database Engine error '80040e14'
>> > Syntax error (missing operator) in query expression '[Date_Completed]
>> > is NULL WHERE (([Customer] LIKE '%Davie%' OR [Address] LIKE '%Davie%'
>> > OR [Post_Code] LIKE '%Davie%' OR [Telephone] LIKE '%Davie%' OR
>> > [Mobile] LIKE '%Davie%' OR [Vehicle] LIKE '%Davie%' OR [Chassis_No]
>> > LIKE '%Davie%' OR [Engine_No] LIKE ''.
>> > /Jobsheet/Datalist.asp, line 227
>> > The code that it highlights is this:
>> > <%
>> > ' Set up Record Set
>> > Set rs = Server.CreateObject("ADODB.Recordset")
>> > rs.CursorLocation = 3
>> > rs.Open sSql, conn, 1, 2 --This line in particular --
>> > nTotalRecs = rs.RecordCount
>> > If nDisplayRecs <= 0 Then ' Display All Records
>> > nDisplayRecs = nTotalRecs
>> > End If
>> > nStartRec = 1
>> > SetUpStartRec() ' Set Up Start Record Position
>> > %>
>> > I would be much obliged if anyone can provide assistance.
>> > Cheers,
>> > Phill- Hide quoted text -
>> - Show quoted text -
>

Begginer needing help to resolve error.

Hi,
I hope one of you may be able to help me with a small probelm I have.
I get the following error:
Microsoft JET Database Engine error '80040e14'
Syntax error (missing operator) in query expression '[Date_Completed]
is NULL WHERE (([Customer] LIKE '%Davie%' OR [Address] LIKE '%Davie%'
OR [Post_Code] LIKE '%Davie%' OR [Telephone] LIKE '%Davie%' OR
[Mobile] LIKE '%Davie%' OR [Vehicle] LIKE '%Davie%' OR [Chassis_No]
LIKE '%Davie%' OR [Engine_No] LIKE ''.
/Jobsheet/Datalist.asp, line 227
The code that it highlights is this:
<%
' Set up Record Set
Set rs = Server.CreateObject("ADODB.Recordset")
rs.CursorLocation = 3
rs.Open sSql, conn, 1, 2 --This line in particular --
nTotalRecs = rs.RecordCount
If nDisplayRecs <= 0 Then ' Display All Records
nDisplayRecs = nTotalRecs
End If
nStartRec = 1
SetUpStartRec() ' Set Up Start Record Position
%>
I would be much obliged if anyone can provide assistance.
Cheers,
Phill
Is it Access query?
"FatboyDim" <webmaster@.pb-enterprises.co.uk> wrote in message
news:1183454575.272248.54230@.c77g2000hse.googlegro ups.com...
> Hi,
> I hope one of you may be able to help me with a small probelm I have.
> I get the following error:
> Microsoft JET Database Engine error '80040e14'
> Syntax error (missing operator) in query expression '[Date_Completed]
> is NULL WHERE (([Customer] LIKE '%Davie%' OR [Address] LIKE '%Davie%'
> OR [Post_Code] LIKE '%Davie%' OR [Telephone] LIKE '%Davie%' OR
> [Mobile] LIKE '%Davie%' OR [Vehicle] LIKE '%Davie%' OR [Chassis_No]
> LIKE '%Davie%' OR [Engine_No] LIKE ''.
> /Jobsheet/Datalist.asp, line 227
>
> The code that it highlights is this:
> <%
> ' Set up Record Set
> Set rs = Server.CreateObject("ADODB.Recordset")
> rs.CursorLocation = 3
> rs.Open sSql, conn, 1, 2 --This line in particular --
> nTotalRecs = rs.RecordCount
> If nDisplayRecs <= 0 Then ' Display All Records
> nDisplayRecs = nTotalRecs
> End If
> nStartRec = 1
> SetUpStartRec() ' Set Up Start Record Position
> %>
> I would be much obliged if anyone can provide assistance.
> Cheers,
> Phill
>
|||Yes,
It is an Access query.
On 3 Jul, 10:27, "Uri Dimant" <u...@.iscar.co.il> wrote:
> Is it Access query?
> "FatboyDim" <webmas...@.pb-enterprises.co.uk> wrote in message
> news:1183454575.272248.54230@.c77g2000hse.googlegro ups.com...
>
>
>
>
>
>
>
> - Show quoted text -
|||Hi
Its SQL Server news group. You will be better of ask the question in Access
group
"FatboyDim" <webmaster@.pb-enterprises.co.uk> wrote in message
news:1183455450.654505.196030@.n2g2000hse.googlegro ups.com...
> Yes,
> It is an Access query.
> On 3 Jul, 10:27, "Uri Dimant" <u...@.iscar.co.il> wrote:
>

Begginer needing help to resolve error.

Hi,
I hope one of you may be able to help me with a small probelm I have.
I get the following error:
Microsoft JET Database Engine error '80040e14'
Syntax error (missing operator) in query expression '[Date_Completed]
is NULL WHERE (([Customer] LIKE '%Davie%' OR [Address] LIKE '%Davie%
'
OR [Post_Code] LIKE '%Davie%' OR [Telephone] LIKE '%Davie%' OR
[Mobile] LIKE '%Davie%' OR [Vehicle] LIKE '%Davie%' OR [Chassis_
No]
LIKE '%Davie%' OR [Engine_No] LIKE ''.
/Jobsheet/Datalist.asp, line 227
The code that it highlights is this:
<%
' Set up Record Set
Set rs = Server.CreateObject("ADODB.Recordset")
rs.CursorLocation = 3
rs.Open sSql, conn, 1, 2 --This line in particular --
nTotalRecs = rs.RecordCount
If nDisplayRecs <= 0 Then ' Display All Records
nDisplayRecs = nTotalRecs
End If
nStartRec = 1
SetUpStartRec() ' Set Up Start Record Position
%>
I would be much obliged if anyone can provide assistance.
Cheers,
PhillIs it Access query?
"FatboyDim" <webmaster@.pb-enterprises.co.uk> wrote in message
news:1183454575.272248.54230@.c77g2000hse.googlegroups.com...
> Hi,
> I hope one of you may be able to help me with a small probelm I have.
> I get the following error:
> Microsoft JET Database Engine error '80040e14'
> Syntax error (missing operator) in query expression '[Date_Completed]
> is NULL WHERE (([Customer] LIKE '%Davie%' OR [Address] LIKE '%Davi
e%'
> OR [Post_Code] LIKE '%Davie%' OR [Telephone] LIKE '%Davie%' OR
> [Mobile] LIKE '%Davie%' OR [Vehicle] LIKE '%Davie%' OR [Chassi
s_No]
> LIKE '%Davie%' OR [Engine_No] LIKE ''.
> /Jobsheet/Datalist.asp, line 227
>
> The code that it highlights is this:
> <%
> ' Set up Record Set
> Set rs = Server.CreateObject("ADODB.Recordset")
> rs.CursorLocation = 3
> rs.Open sSql, conn, 1, 2 --This line in particular --
> nTotalRecs = rs.RecordCount
> If nDisplayRecs <= 0 Then ' Display All Records
> nDisplayRecs = nTotalRecs
> End If
> nStartRec = 1
> SetUpStartRec() ' Set Up Start Record Position
> %>
> I would be much obliged if anyone can provide assistance.
> Cheers,
> Phill
>|||Yes,
It is an Access query.
On 3 Jul, 10:27, "Uri Dimant" <u...@.iscar.co.il> wrote:
> Is it Access query?
> "FatboyDim" <webmas...@.pb-enterprises.co.uk> wrote in message
> news:1183454575.272248.54230@.c77g2000hse.googlegroups.com...
>
>
>
>
>
>
>
>
>
>
>
>
> - Show quoted text -|||Hi
Its SQL Server news group. You will be better of ask the question in Access
group
"FatboyDim" <webmaster@.pb-enterprises.co.uk> wrote in message
news:1183455450.654505.196030@.n2g2000hse.googlegroups.com...
> Yes,
> It is an Access query.
> On 3 Jul, 10:27, "Uri Dimant" <u...@.iscar.co.il> wrote:
>