 |  | Apologies for the shouting but this is important.
When answering a question please:
- Read the question carefully
- Understand that English isn't everyone's first language so be lenient of bad spelling and grammar
- If a question is poorly phrased then either ask for clarification, ignore it, or mark it down. Insults are not welcome
- If the question is inappropriate then click the 'vote to remove message' button
Insults, slap-downs and sarcasm aren't welcome. Let's work to help developers, not make them feel stupid.
cheers, Chris Maunder
The Code Project Co-founder Microsoft C++ MVP
|
|
|
|  | For those new to message boards please try to follow a few simple rules when posting your question.- Choose the correct forum for your message. Posting a VB.NET question in the C++ forum will end in tears.
- Be specific! Don't ask "can someone send me the code to create an application that does 'X'. Pinpoint exactly what it is you need help with.
- Keep the subject line brief, but descriptive. eg "File Serialization problem"
- Keep the question as brief as possible. If you have to include code, include the smallest snippet of code you can.
- Be careful when including code that you haven't made a typo. Typing mistakes can become the focal point instead of the actual question you asked.
- Do not remove or empty a message if others have replied. Keep the thread intact and available for others to search and read. If your problem was answered then edit your message and add "[Solved]" to the subject line of the original post, and cast an approval vote to the one or several answers that really helped you.
- If you are posting source code with your question, place it inside <pre></pre> tags. We advise you also check the "Encode "<" (and other HTML) characters when pasting" checkbox before pasting anything inside the PRE block, and make sure "Use HTML in this post" check box is checked.
- Be courteous and DON'T SHOUT. Everyone here helps because they enjoy helping others, not because it's their job.
- Please do not post links to your question into an unrelated forum such as the lounge. It will be deleted. Likewise, do not post the same question in more than one forum.
- Do not be abusive, offensive, inappropriate or harass anyone on the boards. Doing so will get you kicked off and banned. Play nice.
- If you have a school or university assignment, assume that your teacher or lecturer is also reading these forums.
- No advertising or soliciting.
- We reserve the right to move your posts to a more appropriate forum or to delete anything deemed inappropriate or illegal.
cheers, Chris Maunder The Code Project Co-founder Microsoft C++ MVP
|
|
|
|  | I have a database table with the following schema
CREATETABLE [dbo].[TestScores]( [ID] [int] IDENTITY(1,1) NOTNULL, [Student] [nvarchar](25) NOTNULL, [English] [nvarchar](25) NULL, [Physics] [nvarchar](25) NULL, [Mathematics] [nvarchar](25) NULL, [Engineering] [nvarchar](25) NULL, PRIMARYKEY (ID) ) // Sample Data InsertInto TestScores (Student, English, Physics, Mathematics, Engineering) Values ('Jane', A, B, A, A); InsertInto TestScores (Student, English, Physics, Mathematics, Engineering) Values ('Michelle', A, A, B, A); InsertInto TestScores (Student, English, Physics, Mathematics, Engineering) Values ('Dan, A, A, A, B); I would like to display the results like the following
Student Jane Michelle Dan English A A A Physics B A A Mathematics A B A Engineering A A B I wanted to first Unpivot the data then Pivot the data but I just could not use the Pivot operator on the given data.
Below is my query
Select * from TestScores Unpivot(Course for Courses in (Student, English, Physics, Mathematics, Engineering))as upv Pivot(course for Student in (Jane, Michelle, Dan)) as pv
modified 3 days ago.
|
|
|
| |  | You have a problem with your Unpivot - try removing 'Student' from the column list i.e.
Unpivot(Course for Courses in (English, Physics, Mathematics, Engineering))as upv There is also a problem with the Pivot - you need to use a summary function e.g.Pivot(MAX(course) for Student in (Jane, Michelle, Dan)) as pv Unfortunately if you fix those two problems you get the following results
ID Courses Jane Michelle Dan 1 Engineering A NULL NULL 2 Engineering NULL A NULL 3 Engineering NULL NULL B 1 English A NULL NULL 2 English NULL A NULL 3 English NULL NULL A 1 Mathematics A NULL NULL 2 Mathematics NULL B NULL 3 Mathematics NULL NULL A 1 Physics B NULL NULL 2 Physics NULL A NULL 3 Physics NULL NULL A This is where the article mentioned by @Mycroft-Holmes comes into play OR you can fiddle it like this select Courses, MAX(ISNULL(Jane,'')) as Jane, MAX(ISNULL(Michelle,'')) as Michelle, MAX(ISNULL(Dan,'')) as Dan from (Select * from TestScores Unpivot(Course for Courses in (English, Physics, Mathematics, Engineering)) as upv ) UPV Pivot(MAX(Course) for Student in (Jane, Michelle, Dan)) as pv GROUPBY Courses
|
|
|
|  | Thank you so much for replying. Your solution is 98 percent there, the only problem is that the courses in the result are listed out of order.
In my scenario the order of the courses in the result is trivial. However, in other cases where I have to let's say show companies' earnings by quarter, show companies' stocks by quarter, etc., it will be important.
How can I modify my solution to show the courses in their original order? Thanks again for your help.
modified 3 days ago.
|
|
|
|  | The only solution that comes to mind at the moment (I'll keep thinking!) is to have a separate table listing the courses with an Id field that reflects the order you require e.g.
DECLARE@courseNamestable (id intidentity(1,1), course nvarchar(25)) insertinto@courseNamesvalues ('English'),('Physics'),('Mathematics'),('Engineering') It could just as easily be a permanent table as a table variable. You could use such a table to generate dynamic SQL for the PIVOT if more courses are added). You can then join the previous query to this table and ORDER BY the id on the course table e.g. select cn.id, Courses, MAX(ISNULL(Jane,'')) as Jane, MAX(ISNULL(Michelle,'')) as Michelle, MAX(ISNULL(Dan,'')) as Dan from (Select * from TestScores Unpivot(Course for Courses in (English, Physics, Mathematics, Engineering)) as upv ) UPV Pivot(MAX(Course) for Student in (Jane, Michelle, Dan)) as pv innerjoin@courseNames cn ON pv.Courses=cn.course GROUPBY cn.id, Courses ORDERBY cn.id or if you don't want to include the ID number in the output you could use a CTE ...
;with q as ( select Courses, MAX(ISNULL(Jane,'')) as Jane, MAX(ISNULL(Michelle,'')) as Michelle, MAX(ISNULL(Dan,'')) as Dan from (Select * from TestScores Unpivot(Course for Courses in (English, Physics, Mathematics, Engineering)) as upv ) UPV Pivot(MAX(Course) for Student in (Jane, Michelle, Dan)) as pv GROUPBY Courses ) select q.Courses, q.Jane, q.Michelle, q.Dan FROM q innerjoin@courseNames cn ON q.Courses=cn.course ORDERBY cn.id
|
|
|
|  | Thank you for all your help, your solution using table variable works like a charm.
|
|
|
| |  | Psst! Enhance his rep by upvoting his response, green angle on the left! Never underestimate the power of human stupidity RAH
|
|
|
|  | Hi , I am getting this message on SQL log but i am not initiated any SQL job maintenance. Please help me what this msg indicates.We are taking Drive backup.
Msg: Database backed up. Database: abc, creation date(time): 2015/04/17(08:07:47), pages dumped:56589001, number of dump devices: 1, device information: (FILE=1, TYPE=VIRTUAL_DEVICE: {'{622759E005}7'}). This is an informational message only. No user action is required.
Thanks, Sree
|
|
|
|  | When you take a backup of your disk, you can't just take a copy of the SQL database files. If you did, you could end up with an unusable backup.
Instead, the backup product uses the Volume Shadow Copy Service to communicate with SQL Server. SQL then initiates a proper backup of the databases, writing them out to a virtual device that represents the target of the backup job.
This is perfectly normal, and nothing to worry about.
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
|
|
|
|  | Hi,
I am trying to creat a simple IF - THEN in MySQL but getting a synax error message.
can anyone help please...
here is my statement: IFEXISTS (SELECT payroll_id FROM payroll WHERE location_id = param_location AND payroll_month = param_month AND payroll_year = param_year) THENSET param_payroll_id = 0; END IF; Thanks, Jassim[^]
Technology News @ www.JassimRahma.com
|
|
|
|  | Never used MySql but based on my search, you can't use that syntax in Mysql. Alternate way is, just store the result of query into some variable & use it for comparison to achieve the output. Check this sample MySQL Stored Procedures IF NOT EXISTS()[^]
BTW, always include the complete error message(just 'Syntax error' is not enough) in your question which is better for members to give you answers quickly.
|
|
|
|  | I tried below code but getting same error for the IF--THEN SET param_payroll_exists = (SELECT COUNT(*) FROM payroll WHERE location_id = param_location AND payroll_month = param_month AND payroll_year = param_year); IFEXISTS (param_payroll_exists > 0) THENSET param_payroll_id = 0; END IF; the exact error is:
You have an error in your SQL syntax. Check the manual that corresponds to you MySQL server for the right syntax to use near 'param_payroll_exists > 0) THEN ..........
Technology News @ www.JassimRahma.com
|
|
|
|  | Jassim Rahma wrote: IFEXISTS (param_payroll_exists > 0) THEN
Do you really mean EXISTS here? Software rusts. Simon Stephenson, ca 1994. So does this signature. me, 2012
|
|
|
|  | You didn't get Peter's reply which's fair enough? Just remove EXISTS from that query & run. It's over.
|
|
|
|  | Hello, I am using SQL server 2008 r2. I am new to SQL triggers and trying to call dll from SQL triggers. I have created dll using vb.net,
PublicClass Class1 PublicFunction abc(ByVal a AsString) AsStringReturn a.ToUpper EndFunctionEndClass I have successfully added assembly to the SQL using,
CREATEASSEMBLY triggertest FROM'D:\dll\triggerdll.dll'WITH PERMISSION_SET = SAFE and then added a trigger using,
CREATETRIGGER tri_add_clr ON dbo.foriegn FORINSERTAS EXTERNAL NAME triggertest.Class1.abc Here I am getting error,
Msg 6505, Level 16, State 2, Procedure tri_add_clr, Line 1 Could not find Type 'Class1' in assembly 'triggerdll'. where triggerdll is the name of dll. How to solve this error ? Am I calling dll from SQL trigger properly ? Please help.
modified 1-Jun-16 9:55am.
|
|
|
|  | VB.NET projects have a root namespace[^]. Unless you've cleared that in your project's properties, your class exists within that namespace, and you need to include it within the EXTERNAL NAME specification:
CREATETRIGGER tri_add_clr ON dbo.foriegn FORINSERTAS EXTERNAL NAME triggertest.[YourNamespace.Class1].abc Also:
srikrishnathanthri wrote: CREATEASSEMBLY triggertest FROM'D:\dll\Interop.ADODB.dll' WITH PERMISSION_SET = SAFE
Are you sure that's the correct assembly? That looks like an interop assembly for the ancient "ADODB" library to me.
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
|
|
|
|  | Tried your solution,
Richard Deeming wrote: CREATETRIGGER tri_add_clr ON dbo.foriegn FORINSERT AS EXTERNAL NAME triggertest.[YourNamespace.Class1].abc but I am again getting error,
Msg 6573, Level 16, State 1, Procedure tri_add_clr, Line 1 Method, property or field 'abc' of class'ClassLibrary1.Class1'in assembly 'triggerdll'is not static. Sorry there is a mistake in question about dll name, I have edited that.
|
|
|
| |  | Hello everybody! I have three tables, namely t1, t2, t3
Dim cmdText AsString cmdText = "SELECT t1.StaffName, t2.CampusName FROM t1 INNER JOIN t2 ON t1.CampusID = t2.CampusID ORDER BY t1.StaffName" It is working fine. My problems starts when I want to include t3; such that;
t1.StaffID = t3.StaffID I don't know; how to get it done. Please note that; StaffID is the Primary Key of t1 and the Secondary Key of t3. Would anyone help me, please!
|
|
|
|  | Could you describe the structure of those three tables? We'd usually join between a primary and a foreign key, not a secondary one.
Bastard Programmer from Hell If you can't read my code, try converting it here[^]
|
|
|
|  | Are you just looking for the syntax to join another table?
SELECT ... FROM t1 INNERJOIN t2 ON t2.CampusID = t1.CampusID INNERJOIN t3 ON t3.StaffID = t1.StaffID ORDERBY ... ;
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
|
|
|
|  | Thank you very much, Richard Deeming, for the help. Have a very good day.
|
|
|
|  | Hello,
I have a SQL table with some existing data. In that I have a columns named "Name" and SL No (which is a primary key). For example say I have one entry for that column as "Thilak". Suppose if a next entry comes with same name i.e "Thilak", I want to rename the existing "Thilak" as "Thilak_Slno" and new entry as "Thilak_Slno". And If again any Thilak repeats I want append serial number to that before saving or soon after saving to the database.
The purpose is simple, I am giving option to post a query in my software based on username. while selecting the name, if same name exists in entry that will be difficult to select the Name, if name comes with serial number it will be easier.
So whenever a new entry comes which is same as the existing name, I am planning to append the serial number to the existing names also to the incoming name.
So, now whether it is possible to change the name as it enters into the table ? or should I change once it get saved to database ?
How to do this ? Please help me.
|
|
|
|  | If you want all names to be unique, then just add the serial number in the first place. Then you do not need the extra steps of searching for an existing name and changing it when adding to your database. Alternatively just accept that there may be duplicates which you can process when searching.
|
|
|
|  | You shouldn't change it at all. They are two separate facts, and should each be in their separate field. That way you don't need to "substring" on the name when the numbering changes, and can easily add another field if your combination is no longer unique.
The database is not there to store "formatted" values, but data. Upon retrievel, you paste to two fields together and have what you want.
Bastard Programmer from Hell If you can't read my code, try converting it here[^]
|
|
|
|  | Hello,
I am using SQL express 2008 r2. Some times while running SQL backup query, Text
BACKUPDATABASE [DBName] TOdisk = 'TargetPath'WITH CHECKSUM I am getting the error 'detected an error on page'. But if I run query without checksum then it runs successfully.
My question is,
1. Why that error is coming ?
2. What should I do if that error comes ?
3. Can I rely on the backup without checksum ?
Please help me.
|
|
|
|  | Sounds like you might have some page-level corruption in your database.
Try running:
DBCC CHECKDB (N'Your-Database-Name') WITH NO_INFOMSGS, ALL_ERRORMSGS; If you still need help, you'll need to post the full error message.
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
|
|
|
|  | This is the error I am getting,
Msg 3043, Level 16, State 1, Line 1 BACKUP 'broken' detected an error on page (1:143) in file 'c:\sql\mydb.mdf'. Msg 3013, Level 16, State 1, Line 1 BACKUP DATABASE is terminating abnormally.
|
|
|
|  | That error message means your database is corrupt. Try running DBCC CHECKDB , as I suggested.
You'll probably need to restore your database from the most recent valid backup.
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
|
|
|
|  | Brent Ozar recently published a great blog-post covering the details of what you need to do: What to Do When DBCC CHECKDB Reports Corruption[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
|
|
|
|  | Good Day All
i have been using the below declared Cursor from the Stored-procedure for around 3 years now. The last couple of weeks i have been getting the error
Incorrect syntax near the keyword 'CROSS'.
I dont have a Cross Join in this Cursor and this started after Infrastructures upgraded the hardware on the SQL Server , i noticed other settings were lost but was able to recover them. USE [DBPS] GOSET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGO ALTERPROC [dbo].[DATABASE_MAINTANANCE_PLAN] ASDECLARE@DatabaseName SYSNAME = DB_NAME(), @TableNameVARCHAR(256) DECLARE@FILLFACTORINT = 85DECLARE@DynamicSQLNVARCHAR(max) = 'DECLARE curAllTablesInDB CURSOR FOR SELECT TABLE_SCHEMA + ''.'' + TABLE_NAME AS TABLENAME FROM ' + @DatabaseName + '.INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = ''BASE TABLE''' BEGINEXEC sp_executeSQL @DynamicSQLOPEN curAllTablesInDB FETCH NEXT FROM curAllTablesInDB INTO@TableNameWHILE (@@FETCH_STATUS = 0) BEGINSET@DynamicSQL = 'ALTER INDEX ALL ON ' + @TableName + ' REBUILD WITH (FILLFACTOR = ' + CONVERT(VARCHAR,@FILLFACTOR) + ')'PRINT@DynamicSQLEXEC sp_executeSQL @DynamicSQLFETCH NEXT FROM curAllTablesInDB INTO@TableNameENDCLOSE curAllTablesInDB DEALLOCATE curAllTablesInDB END Thanks Vuyiswa Maseko, Spoted in Daniweb-- Sorry to rant. I hate websites. They are just wierd. They don't behave like normal code. C#/VB.NET/ASP.NET/SQL7/2000/2005/2008 http://www.vimalsoft.com vuyiswa[at]vimalsoft.com
|
|
|
|  | Thanks
I had a table named "CROSS" Cross is a keyword in SQL , that caused a problem for that Dynamic Query. Thanks its resolved now. Vuyiswa Maseko, Spoted in Daniweb-- Sorry to rant. I hate websites. They are just wierd. They don't behave like normal code. C#/VB.NET/ASP.NET/SQL7/2000/2005/2008 http://www.vimalsoft.com vuyiswa[at]vimalsoft.com
|
|
|
|  | Rather than using dynamic SQL and a cursor, why not use the undocumented sp_MSforeachtable procedure[^]?
ALTERPROC [dbo].[DATABASE_MAINTANANCE_PLAN] ASBEGINDECLARE@commandnvarchar(max); DECLARE@FillFactorint = 85; SET@command = N'ALTER INDEX ALL ON [?] REBUILD WITH (FILLFACTOR = ' + Convert(nvarchar(3), @FillFactor) + N')'; EXEC sp_MSforeachtable @command; END
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
|
|
|
|  | Hello,
I am planning to migrate from MSFlexGrid to MsHflexGrid. In MSFlexGrid, when the .col /.row property is changed programmatically, the rowcolchange event gets fired. But in MsHflexGrid the same doesn’t work. However, on manually changing the .col/.row property through mouse click or using navigation keys, the event gets fired in MSHFlexGrid
Please help.
|
|
|
|  | I think you may be better off asking this question in QA[^]. As this seems to be more about changing your grid control than actual database systems.
Every day, thousands of innocent plants are killed by vegetarians.
Help end the violence EAT BACON
|
|
|
|  | You are going to have a lot of problems getting support for vb6 controls, it is a dead language.
You would be better served by scrapping the entire application and rewriting in a current language where you can get support. Never underestimate the power of human stupidity RAH
|
|
|
|  | Hello,
I am using Microsoft SQL server 2008. I have 2 SQL tables Table 'Product1' and Table 'Product2'. In 'Product1' Table I have columns named
1.SLNO,
2.Name,
3.Place
4.State
And 'Product2' have columns named,
1.SLNO,
2.Name,
3.Place
4.State
5.regno
here 'regno' if FK to 'SLNO' (of product1 table ).
My requirement is to update the columns in 'Product2' table when I modify data in 'Product1' table ( 'name' 'Place' and 'state' column). Is it possible to update 'Product2' table without running individual queries for each rows ?
If yes how to do this ?
Please help.
|
|
|
|  | Since the columns in Product2 always have to match the columns in Product1 , wouldn't it make more sense to remove them from the Product2 table? Otherwise, you're just duplicating data for no reason.
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
|
|
|
|  | yes you are right. But for time being I cannot do that. However I got a one method which partially works. Here it goes..
So I have added 'Unique constraint' for 3 columns (Name, Place and State) in table1 table using,
ALTER TABLE table1 ADD UNIQUE(column) and created foreign key in table2 table using,
ALTER TABLE table2 ADD FOREIGN KEY (column) REFERENCES table1(column); While adding 'ON DELETE CASCADE' to table2 I am getting error, that
"There are no primary or candidate keys in the referenced table" Is it possible to set ''ON DELETE CASCADE" without adding primary key in the parent table ?
Also how to add "ON DELETE CASCADE" for some foreign keys ? In my case I have 3 foreign keys ( Name, Place and State). But I want to add "ON DELETE CASCADE" only for Place and State.
Please help.
|
|
|
|  | srikrishnathanthri wrote: Is it possible to set ''ON DELETE CASCADE" without adding primary key in the parent table ?
A foreign key must reference either a primary key, or a column with a unique constraint. To set up a foreign key between the tables, you'll need a unique constraint on the SLNO column in table1.
srikrishnathanthri wrote: But I want to add "ON DELETE CASCADE" only for Place and State.
I don't think you've understood what ON DELETE CASCADE means. When you delete the row from table1, any rows in table2 with the same SLNO will be deleted as well. It doesn't do anything when you change a value in the referenced row, and it doesn't delete the value from specific columns.
Cascading Referential Integrity Constraints[^]
You could do this with a trigger[^] on table1, but it's a pretty nasty workaround, which can lead to hard-to-trace problems. As it's only two tables, it would be simpler to update both at the same time.
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
|
|
|
|  | Ok. I got your second point, yes now I understood 'ON DELETE CASCADE' correctly. But I have doubt in my first question.
Here I am referring foreign key to a column with a unique constraint. I have created foreign keys refereeing to unique constraint without any error.
The point I am getting error is when I run,
ALTER TABLE [dbo].[Product2] ADD CONSTRAINT [FK_ProductDetails_Products] FOREIGN KEY([name],[place],[state]) REFERENCES [dbo].[Product1] ([name],[Place],[state]) ON UPDATE CASCADE ON DELETE CASCADE Can you guess what might be the error.
|
|
|
|  | Do you have a unique constraint on Product1 for name, place and state?
ALTERTABLE dbo.Product1 ADDCONSTRAINT UX_Product1_Name_Place_State UNIQUENONCLUSTERED (name, Place, state) If not, you can't create a foreign key pointing to it.
If you have, then you'll probably get an error relating to multiple cascade paths, since you already have a foreign key relationship between the two tables.
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
|
|
|
|  | Now I have a doubt, I want to another column named 'regno' and I want to make it primary key of product1. Now is it possible to add FK in prodcut2 for regno, name, state and place. ? Because I am getting an error..
Introducing FOREIGN KEY constraint 'FK_ProductDetails_Products' on table 'Product2' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. In my case, regno refers to Prooduct1's regno ( which is primary key) name, place and state refers to Prooduct1's name, place and state ( which are unique constraints )
Why I am getting this error ?
|
|
|
|  | Because you have multiple FKs between the tables. It's a bad design, but it's possible - so long as only one of the FKs specifies a "cascade" rule for update or delete.
[A] table cannot appear more than one time in a list of all the cascading referential actions that are started by either a DELETE or an UPDATE statement.
You're trying to use a foreign key for something that it wasn't designed for. If you can't change the table design, switch to issuing multiple queries, or using a trigger to push the changes from Product1 to Product2.
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
|
|
|
|  | Hi
I would suggest you spend some time understanding Normalization of tables and reference integrity. If you have a good understanding of these concepts then it will be a lot easier for you designing the tables in the right way and fixing any errors.
|
|
|
|  | Hi,
In MySQL, I have basket field call item_name in my order_basket table.
I want an SQL statement to take all item_name and INSERT it into a variable call param_details whch a TEXT type with a "\n" between them.
something like this DECLARE param_details text; INSERT CONTACT(item_name, "\n"INTO param_details FROM order_basket How can I do this please?
Thanks, Jassim[^]
Technology News @ www.JassimRahma.com
|
|
|
|  | DECLARE@varASNVARCHARSELECT@var = field1 FROM table1 WHERE ... Skipper: We'll fix it. Alex: Fix it? How you gonna fix this? Skipper: Grit, spit and a whole lotta duct tape.
|
|
|
|
|