0

Normally in asp.net I can run many queries one after another to create my temp tables. We pull from a lot of tables so its a huge speed advantage. I would then do a select from #999.

GOAL:

This is one of my pages in asp.net:

    sql.Append("Create Table #999 (SvID varchar(15) Default '', SvcID int Default ((0)), Value varchar(50) Default '', Store varchar(10) Default '', StoreID int Default ((0)), VisitDate varchar(100) Default '', Lead varchar(100) Default '',  LeadID int Default ((0)),ShipTo varchar(100) Default '', ShipToAddress varchar(300) Default '', Parts Varchar(5000) Default '', ShipToID int Default ((0)), ShipToType Varchar(50) Default '', ProjID int Default ((0)), DivID Int Default ((0)), Combined int Default ((0)), HasTime int Default ((0)), DateOK Int Default ((0))); ");

    //Insert StoreVisitID's
    sql.Append("Insert into #999 (SvID) Select Distinct ID from StoreVisit where projid =" + ProjID + "; ");

    //Update Store Visit Info
    sql.Append("Update #999 Set SVcID = sub.svcid, Store = sub.Store, StoreID = sub.StoreID, ProjID = sub.ProjID, LeadID = sub.TeamLeadID, VisitDate = sub.VisitDate, DivID = sub.DivID, Value = sub.Status from #999 h Join (select svcID, Store, StoreID, ProjID, ID, TeamLeadID, Convert(Varchar, Visitdate, 1) as VisitDate, DivID, Status  From StoreVisit where projid =" + ProjID + ") as sub on sub.id = h.svid; ");

    //Update Store Visit Lead
    sql.Append("Update #999 Set Lead = sub.Lead From #999 h Join ( Select id, FirstName + ' ' + LastName as Lead From Employee) as sub on sub.id = h.LeadID; ");

    //Update ShipToID, ShipToType
    sql.Append("Update #999 Set ShipToID = sub.ShipToID, ShipToType = sub.ShipToType From #999 h Join ( Select SviD, ShipToID, ShipToType from StoreVisit2) as sub on sub.svid = h.svid; ");

    //Ship To Other Employee
    sql.Append("Update #999 Set ShipTo = Sub.Lead + ' - Employee', ShipToAddress = sub.Address From #999 h  Join (Select id, FirstName + ' ' + LastName as Lead, Address + '. ' + Address2 + ', ' + City + ', ' + State as Address From Employee) as sub on sub.id = h.ShipToID Where ShipToType='E' and ShipToID <> 0; ");

ISSUE:

In php I am trying to do the same thing with prepared statements.

Attempt1: The code is below. I'm getting invalid object #ViewQuestionComments error on the second execute.

Attempt2: I tried to prepare each sql and then execute once and I get the same error on that execute.

Attempt3: I also tried to concatenate all the sql and run in one prepare and execute statement with the same error.

Any suggestions on how to do this the right way?

Here is the code I'm running.

        $sql = "IF OBJECT_ID('#ViewQuestionComments', 'U') IS NOT NULL DROP TABLE #ViewQuestionComments; Create Table #ViewQuestionComments (CommentID int default ((0)), UserID int default ((0)), Comment varchar(max)  default '', DateModified smalldatetime, UserName nvarchar(200) default '', Points int default ((0)))";
        $stmt = $PDO->prepare( $sql );
        $stmt->execute();
        $sql = "Insert Into #ViewQuestionComments (CommentID, UserID, Comment, DateModified)  select ID, UserID, Comment, DateModified from hanoncs_askme.hanoncs_hanoncs.Comments Where PostID=? and Status=1";
        $stmt = $PDO->prepare( $sql );
        $stmt->bindParam(1, $QuestionID);
        $stmt->execute();

        $sql = "Update #ViewQuestionComments Set UserName = m.UserName From #ViewQuestionComments c Left Join hanoncs_securelogin.hanoncs_hanoncs.members m on m.id = c.UserID";
        $stmt = $PDO->prepare( $sql );
        $stmt->execute();

        $sql = "Update #ViewQuestionComments set Points = (Select count(*) from hanoncs_askme.hanoncs_hanoncs.CommentVotes where PostID=c.CommentID) From #ViewQuestionComments c";
        $stmt = $PDO->prepare( $sql );
        $stmt->execute();

        $sql = "Select * from #ViewQuestionComments";
        $stmt = $PDO->prepare( $sql );
        $stmt->execute();
        $rows6 = $stmt->fetchAll(PDO::FETCH_BOTH);

2 Answers 2

1

Regardless of the fact that your senior programmers do not like them, I often make use of stored procedures where it makes sense to do so.

From my first hand experience most sql activities, that are not a single select, update, insert, or delete statement, can benefit from being in a stored proc. As with any tool in the toolbox, it depends on what you are doing. When I build temp tables, it is done within a stored proc because it is a complex action and very often has a large volume of sql involved.

In your example, checking object existence, dropping it, building a new db object, adding data, and then pulling that data out is, imho, a series actions that would strongly suggest a stored proc. Others may argue for some layer of data access objects. Regardless, you do WANT to encapsulate this to keep your product maintainable. Stored procs do that well. They also require less network traffic than sending the component sql statements one at a time. They will generally run faster than in-line sql too and not just because of network latency, one of the many things a database does is generate an execution plan for any sql it runs and while prepared statements help, stored procedures help more. By far, the biggest complaint people have about them, from what I have seen, is sql not as robust a programming language as things like java or C# or Objective C or any number of other languages. There are other things that people list as cons but imo being able to do what you need to do with ease and efficiency is the top one.

Again, they are one of the tools in the toolbox and, like any tool, there is a time and place to use them. But don't unilaterally dismiss them, that would be a mistake. Personally, over the years I have gotten very good a using them and as my abilities and knowledge of sql has increased, I've found even better uses for them. Learn about all the tools.

Have a look at the t-sql doc for Creating Stored Procedures If you want more on pros and cons of stored procs then the internet is full of that, among other things. Here are a few links.

Determine when to use stored procedures vs. SQL in the code

Why use Stored Procedures?

Stored Procedures Are Evil

Google "stored procedures vs inline sql" and you will get lot more. Just remember, the right tool for the right job.

Sign up to request clarification or add additional context in comments.

5 Comments

Yes my title says MS SQL as well. Ill take a look.
Knowing the version would allow linking directly to that version's docs. Still you can switch versions once you follow the link.
Thanks for updating your answer. I just read this, programmers.stackexchange.com/questions/158534/… and the answers and comments have some good arguments against using stored procedures. As we don't have a DBA and I am not the best at tuning SQL. We also have multiple programmers. So I think I may just keep the SQL in code.
I would hope that the system designer(s) there would have some form of encapsulation for often used/reused sql. If not stored procs then a set of classes at least. If the project is of any size and someone cares about what they are designing, this encapsulation is a must have for the sake of future maintainability. I wish you good fortune and strongly suggest you take every opportunity to expand your skills in the area of sql as far as you can. Used well, it can be a powerful tool.
@Hanoncs I agree with WillG sp are the way to go for this situation, the question you looked up is about putting business logic which is not desirable. but for multiple queries this is what is needed
1

Use a stored procedure, it is not that hard:

CREATE PROC updateQuestion ()
 AS
 BEGIN
    BEGIN TRANSACTION

        IF Object_id('#ViewQuestionComments', 'U') IS NOT NULL DROP TABLE #viewquestioncomments;
        CREATE TABLE #viewquestioncomments 
                     ( 
                                  commentid INT DEFAULT ((0)), 
                                  userid    INT DEFAULT ((0)), 
                                  comment   VARCHAR(max) DEFAULT '', 
                                  datemodified SMALLDATETIME, 
                                  username NVARCHAR(200) DEFAULT '', 
                                  points   INT DEFAULT ((0)) 
                     );
                     INSERT INTO #viewquestioncomments 
                    ( 
                                commentid, 
                                userid, 
                                comment, 
                                datemodified 
                    ) 
        SELECT id, 
               userid, 
               comment, 
               datemodified 
        FROM   hanoncs_askme.hanoncs_hanoncs.comments 
        WHERE  postid=? 
        AND    status=1;
        UPDATE #viewquestioncomments 
        SET       username = m.username 
        FROM      #viewquestioncomments c 
        LEFT JOIN hanoncs_securelogin.hanoncs_hanoncs.members m 
        ON        m.id = c.userid;
        UPDATE #viewquestioncomments 
        SET    points = 
               ( 
                      SELECT Count(*) 
                      FROM   hanoncs_askme.hanoncs_hanoncs.commentvotes 
                      WHERE  postid=c.commentid) 
        FROM   #viewquestioncomments c;
        SELECT * 
        FROM   #viewquestioncomments";

     IF @@ERROR != 0
        ROLLBACK TRANSACTION
        ELSE
            COMMIT TRANSACTION
 END

GO

Usage:

$stmt= $PDO->prepare('EXEC updateQuestion');
$stmt->execute();

16 Comments

I made an edit to my question. Please see towards the bottom.
Thanks, I tried that: SET NOCOUNT ON;. but still get the error.
This: 'EXEC [hanoncs_hanoncs].[CommentsTemp] @QuestionID = 1' works perfect in management studio.
does it return anything, are you fetching
i am getting the error on this: $rows6 = $stmt->fetch(PDO::FETCH_BOTH);
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.