Creating Stored Procedures Based On Variables

Oct 5, 2006

Hi There,

I would like to know if for example i have some tables in my DataBase and i need from each table to get for instance, the Name by the ID, how can i make only one procedure which use parameters and variables so i can use this SP to get the Name By ID for all the Tables?

Thanks

View 1 Replies


ADVERTISEMENT

Stored Procedures Variables

Dec 28, 2005

I have a PROC that I want to modify via a variable I will pass in from ASP.Net.

Currently the PROC is as follows:

ALTER Procedure [dbo].[spu_FindProperties]
@Search varChar(30)
AS
Set @Search = '%'+ @Search + '%'

SELECT dbo.EDCclient.CLIENT, dbo.EDCclient.CLIENT_ID, dbo.EDCproperty.PROPERTY, dbo.EDCproperty.PROP_ID, dbo.EDCproperty.CLIENT_ID AS Expr1,
dbo.EDCproperty.TRACKER, dbo.EDCproperty.SUBTRACKER, dbo.EDCproperty.PHONE, dbo.EDCproperty.APT_UNITS, dbo.EDCproperty.ESP,
dbo.EDCproperty.CTRLS_INST, dbo.EDCproperty.TODO, dbo.EDCproperty.SWO
FROM dbo.EDCclient INNER JOIN
dbo.EDCproperty ON dbo.EDCclient.CLIENT_ID = dbo.EDCproperty.CLIENT_ID
WHERE (dbo.EDCclient.CLIENT like @Search) OR
(dbo.EDCproperty.PROPERTY like @Search)

I now want to modify it so that the entire Where clause is created in ASp and passed in. So I think my new PROC should look as follows:

ALTER Procedure [dbo].[spu_FindProperties]
@Search varChar(200)
AS

SELECT dbo.EDCclient.CLIENT, dbo.EDCclient.CLIENT_ID, dbo.EDCproperty.PROPERTY, dbo.EDCproperty.PROP_ID, dbo.EDCproperty.CLIENT_ID AS Expr1,
dbo.EDCproperty.TRACKER, dbo.EDCproperty.SUBTRACKER, dbo.EDCproperty.PHONE, dbo.EDCproperty.APT_UNITS, dbo.EDCproperty.ESP,
dbo.EDCproperty.CTRLS_INST, dbo.EDCproperty.TODO, dbo.EDCproperty.SWO
FROM dbo.EDCclient INNER JOIN
dbo.EDCproperty ON dbo.EDCclient.CLIENT_ID = dbo.EDCproperty.CLIENT_ID

@Search)

But I can't get SQL to accept the @Search in place of the Where... Any ideas?

View 7 Replies View Related

Need Help Wioth Variables In Stored Procedures

Mar 15, 2007

I'm working on my first stored procedure, having just watched a video about how to use them.  I have a working procedure that looks like this:set ANSI_NULLS ONset QUOTED_IDENTIFIER ONGOALTER PROCEDURE [dbo].[InMateSearch]    @State nvarchar(255)   AS       BEGIN    DECLARE @SqlString nvarchar(255)       SELECT [FIRST NAME], [LAST NAME], [STATE]     FROM members     WHERE suspend=0 AND (State=@State OR Country=@State)ENDWhat I need to do is build the WHERE clause of the SELECT Statement based on the values of the parameters passed in.  There will be a lot of them, but State will do for an example.I want to assign a variable, say SqlString  = " suspend=0".  Then I want to check the value of @State which is a parameter being passed in, then do something like this:If @State <> "" then SqlString = SqlString & " AND (State=@State OR Country=@State)" so that I'm only filtering by state if the state parameter isn't empty.  Then I would like my SELECT statement to look like: SELECT [FIRST NAME], [LAST NAME], [STATE]  FROM members  WHERE (SqlString)I'm declaring SqlString as the video indicated, but in the video the variable is assigned a value from the database.  I think I need a different kind of variable.  If I try to do something like SqlString = "test" or @SqlString = "test" I get an error.  Once I define or declare a variable I can use to build the string, how do I assign it to the WHERE clause?Diane  

View 3 Replies View Related

Stored Procedures With Output Variables

May 25, 2007

Hi,



What is the syntax calling a stored procedure (let say named 'myproc') with OUTPUT variables (lets say the proc has an integer output variable named 'myvar') ?



Thanks,

Dror.

View 10 Replies View Related

SQL 2012 :: Parsing Variables Between Stored Procedures

Oct 20, 2014

I've got a number of stored procedures that I have for reporting

All are of a similar starting format

For easier maintenance and to take away the need to change all of them if the methodology changes I want to split out shared code.

What I want to do is to take out the part that populates the @ID1 table into a separate stored proc which will be called from the report procs. The values from the shared proc will then be parsed back to the reporting proc.

I thought about using a function but I don't think it will be flexible enough as in certain cases I want to parse 2 or more IDs back into the final output.

I also don't want to make the code too complex so that it is relatively easy to read

CREATE PROC dbo.ReportM1 @ID INT AS
DECLARE
@ID1 TABLE (ID INT PRIMARY KEY, UNIQUE(ID))
IF @ID = 0
INSERT INTO @ID1

[Code] ....

The first question I have is: can i do it with a table variable when going between procs or do i need to build a real table if i want it to maintain the logic in 1 place.

May be worth bearing in mind that the end user who will be executing the proc will only have read + execute stored proc access permissions so dropping, updating or creating real tables is not an option. #Temp tables are possible but since am using table variables throughout would prefer to stick with them.

View 2 Replies View Related

Memory Usage For Local Variables In Stored Procedures

Jul 3, 2003

I would like to know if there is a penalty for Varchar variables in stored procedures if I declare them Varchar(8000) instead of Varchar(1000).
I have a lot of variables and sometimes the content will be more them 1000 characters.
Is memory only allocated for the the actual contents or for the complete declared length?

View 2 Replies View Related

SSIS Updating Package Variables From Stored Procedures

Jul 31, 2007


I have been looking at the project Real reference implementation for doing auditing of data uploads. The tables and store procedures are in place using identical field and variable names. However, when running the package it does not update the relevant log entry with the end time and status.

I have performed the process manually running the stored procedures, providing the values directly and everything works fine.

I can only assume that the LogID variable is not being updated during the run and therefore the onEnd procedure cannot update the relevant log entry.

One side effect is that it does update the record when it€™s the first record entered into the table but not on any other inserts. Clearing the table each time is not an option.

This has become rather frustrating and would appreciate any assistance.

Thanks.

View 1 Replies View Related

XML BASED STORED PROCEDURES

Jul 11, 2007

 Hello friends.Can u please guide me to the links or other info about how to write xml based stored procedures.Your help will be very much appreciated.Thank you.gurjeetsaini@gmail.com 

View 2 Replies View Related

Reports Based On Stored Procedures

Jan 3, 2008



I have a stored procedure that returns two tables which I use in VB .NET to populate a DataSet.

Is it possible to use the same stored procedure to act as the datasource for a report and subreport in reporting services?

The only way I have found so far would be to either run the stored proc twice (one for each report) or dump the data into temporary tables.

View 1 Replies View Related

How To Create CLR Based Stored Procedures

May 3, 2006

I need to create CLR Based Stored Procedures using VS2005 Standard Edition in Sql Server 2005 Standard Edition. Unfortunately, when I create a new project in VS2005. I can not find the template to create a Sql server project using C#. I re-install sql server and Vs2005, the problem still there. Does Vs2005 standard edition support create sql server project? Thanks a lot.

View 1 Replies View Related

Stored Procedures Are Not Creating

Dec 4, 2001

I want to create a replication on PUBS database between the servers "DENVER" and "VANCOUVER". I created a publication on "DENVER" using SALES table of PUBS database. In the properties of publication, I selected all the options of "Subscription creation and synchronization" under "Subscription options".

Then I created a pull subscription on "VANCOUVER" using PUBS database. As data of SALES table is same in both servers and also I want to use subscribers schema and data, I chose the option "No, the subscriber already has the schema and data" for initializing subscription. Now the problem is when I do updations in sales table, subscription is returning error "Could not find stored procedure 'sp_MSupd_sales'". I was found that subscription is not creating any of the stored procedure that is needed for subscribing from publication. Please help me to solve this problem.

Thanking You all,

Vishnu

View 1 Replies View Related

Creating Stored Procedures

Apr 23, 2008



Hi,All,I want to create a stored procedure,it should accept two input parameters one is General variable and other one is Table name.
How to pass table name as a input parameter.
I have created following one,but giving error.

CREATE PROC SP_VOTERSLIPS @BOOTHID VARCHAR(14),@TABLENAME VARCHAR(255)
AS
BEGIN
SELECT V.BOOTHID,B.BOOTHNAME,B.BOOTHADDR1,B.BOOTHADDR2,B.ENGBOOTHADDR1,B.ENGBOOTHADDR2,C.CONSSTUTIONNAME,V.SNO,V.HOUSENO,V.VOTERNAME,
V.GUARDIANTITLE,V.GUARDIANNAME,V.GENDER,V.AGE,V.VOTERIDNUMBER FROM @TABLENAME V LEFT JOIN TBLBOOTH B ON (B.BOOTHID=V.BOOTHID) LEFT JOIN
TBLCONSTTUTION C ON (C.CONSSTUTIONID=V.CONSSTUTIONID) WHERE B.BOOTHID=@BOOTHID
END


Error is :Must declare the variable '@TABLENAME'.

Pls Help me,it is urgent.

View 5 Replies View Related

Creating Stored Procedures In Sql Server

Jul 2, 2007

I just installed sql server 2005 on my machine.  I've been using Access for some time and have created my stored procedures easily in it.  However, this sql server 2005 is so complicated.  In Access, all I had to do was "Create a New Query", write my sql statement, name and save it.   However, I am having so much trouble with this sql server.  For example, when I create a stored procedure in sql server, it has a .sql extension.  I am assuming the stored procedure is a file.  However, after saving it, I expand my database, expand programmability, and expand stored procedures, yet my new stored procedure is not there.  It's placed in a file called projects.  I need to access this stored procedure from code, but in visual studio, I get an error message, "Cannot find stored procedure sp_Roster".  Here is the code I used to access my stored procedure from vb.net.  I thought it would work but it didntDim comm As New SqlCommandDim strsql As StringDim strconn As String        strsql = "sp_Roster"        strconn = "server=Home; user=sa; pwd=juwar74; database=Book;"        With comm            .Connection = New SqlConnection(strconn)            .CommandText = strsql            .CommandType = CommandType.StoredProcedure            With .Parameters.Add("TeacherID", SqlDbType.Char)                .Value = "DawsMark@aol.com"            End With            With .Parameters.Add("ClassID", SqlDbType.Int)                .Value = CInt(classid)            End With            With .Parameters.Add("sID", SqlDbType.Int)                .Value = ssID            End With            With .Parameters.Add("sLastName", SqlDbType.Char)                .Value = lastname            End With            With .Parameters.Add("sFirstName", SqlDbType.Char)                .Value = firstname            End With            With .Parameters.Add("sMiddleName", SqlDbType.Char)                .Value = middlename            End With            With .Parameters.Add("Student", SqlDbType.Char)                .Value = fullname            End With            With .Parameters.Add("Password", SqlDbType.Char)                .Value = password            End With            .Connection.Open()            .ExecuteNonQuery()            With comm.Connection                If .State = ConnectionState.Open Then                    .Close()                End If            End With        End With Here is my procedure that I created and that was saved as sp_Roster.sql in sql server CREATE PROCEDURE sp_Roster     ASBEGIN       SET NOCOUNT ON;    -- Insert statements for procedure here    INSERT INTO Roster (TeacherID, ClassID, sID, sLastName, sFirstName, sMiddleName, Student, Password) VALUES (@TeacherID, @ClassID, @sID, @sLastName, @sFirstName, @sMiddleName, @Student, @Password)ENDGO Why isn't ado.net finding it in sql server.  Is the sqlstr correct?  

View 2 Replies View Related

Creating Multiple Stored Procedures At Once

May 1, 2008

Hey

I am creating a database application that is accessed through a .NET front end.
What I want to do is run a SQL script that will create my DB, create my indexes and enforce my constraints (all of which I have done) but I also want to create my stored procedures in the same script also.

When I merge all my stored procedures (about 16) into one file and run it in SQL Query Analyzer I get multiple errors but the one that is coursing me the most bother is

‘Server: Msg 156, Level 15, State 1, Procedure procedureName, Line 134
Incorrect syntax near the keyword 'procedure'.’

What does this mean and why can’t I run more than once Stored Procedure at once?


Many thanks

Quish

View 2 Replies View Related

Creating Charts Using Stored Procedures

Jul 21, 2006

Hi all,

I want to create charts(pie/bar) using stored procedures for the table record values in sql server 2005 express edition.

plz help me for the above topic

Thanks & Regards,
Srinivas

View 6 Replies View Related

Creating Multiple Stored Procedures In One Go.

Feb 25, 2008



I have 50-60 stored procedures in my application and these are stored in different files as per file one stored procedudre.

I want to deploy my applicaiton. I want to create a batch or Single SQL file to create all stored precodures in on go.

My objective is to ensure that No stored procedure has left while deploying the applicaiton.

thanks.

View 3 Replies View Related

Creating Multiple Stored Procedures At Once

May 1, 2008

Hey

I am creating a database application that is accessed through a .NET front end.
What I want to do is run a SQL script that will create my DB, create my indexes and enforce my constraints (all of which I have done) but I also want to create my stored procedures in the same script also.

When I merge all my stored procedures (about 16) into one file and run it in SQL Query Analyser I get multiple errors but the one that is coursing me the most bother is

€˜Server: Msg 156, Level 15, State 1, Procedure procedureName, Line 134
Incorrect syntax near the keyword 'procedure'.€™

What does this mean and why can€™t I run more than once Stored Procedure at once?


Many thanks

Quish

View 9 Replies View Related

Creating SQL Server Stored Procedures In Deployment

Sep 20, 2007

Hey guys,I'm having a problem. I've been given a task to complete. I was given a database, and asked to wrap a website around it with certain functionality. I did this, and added seven stored procedures in the proccess. Everything works, Business Logic Layer, Data Access Layer, error validation, even screwed around with SQL-injection protection. Lovely, yes?However, when my little website gets tested, it's going to be plugged into a fresh database - the exact same database I was given, only with different data in the tables. My stored procedures won't be in that database. I can detect if my stored procedure doesn't exist easily enough by catching the error at runtime and checking the code. I would like to create the stored procedure inside that catch block. I just don't know how.The easy answer is just to use embedded SQL in my application instead of stored procedures. This isn't a commercial application, it's just a task I've been given to test my abilities. But embedded SQL is icky. I'd rather do it properly.

View 1 Replies View Related

Creating Extended Stored Procedures In C Sharp ?

Apr 26, 2004

Is it possible to create an extended stored procedure in C Sharp.
This is for Sql Server 2000.

Books online mentions that you have to use c / c++ to create an extended stored procedure.
However have Microsoft added any support so that the same thing can be done through a simpler language like C Sharp.

Thanks,
Alok.

View 1 Replies View Related

Creating Stored Procedures In SQL Server 2000

Dec 12, 2006

sivanantham writes "How to create Stored Procedures in SQL Server 2000?

also give me samples with Cursors and all

Thanks
Sivanantham"

View 4 Replies View Related

Creating Stored Procs Based On SQL Server Version

Jul 20, 2005

We have a product that we were experiencing high recompile rates do totemp tables, we have re-written them to use table variables to reducerecompile rate. The problem I am having is that we have somecustomers still on SQL 7 where the table variables were not valid. Iwould like to have one installation script that would create thestored procedure with table variables on SQL Server 2000 and withouton SQL Server 7, I have been unsuccessful do to the limitation thatCREATE PROCEDURE statement cannot be in a script with any otherstatements.Was wondering if anyone else has run into this and found a way aroundit.

View 1 Replies View Related

Error When Creating Script To Copy Stored Procedures

Jan 16, 2007

Our DB has around 30 SProcs - I need to move them into a script, so that it can be easily added to another server. The way I'm creating the script is to highlight all the SProcs, then copy - in my notepad screen, I paste, which gives me one script, which includes all the individual creation scripts for the Sprocs.
 However, I'm getting an error when I create the script -
Cannot add rows to sysdepends for the current stored procedure because it depends on the missing object 'SP_MySproc'. The stored procedure will still be created.
So - what's a good, and/or easy way to structure the script, so that I can easily find WHERE to put Which SProc Script, in the list?
 

View 4 Replies View Related

SSMS-EE: Creating And Using Stored Procedures - Error Messages 111, 156, &&amp; 102

May 10, 2006

Hi all,

I tried to use the SSMS-EE Query to execute the following code statements:

--- SQLQuery.sql---

USE testDB
DECLARE @procID int
DECLARE @procName varchar(20)
DECLARE @procType varchar(20)
CREATE PROC sp_getRecords AS SELECT * FROM Inventory
CREATE PROC sp_insertRecord @procID int, @procName varchar(20), @procType
varchar(20) AS INSERT INTO Inventory VALUES (@procID, @procName, @procType)
CREATE PROC sp_deleteRecord @procID int AS DELETE FROM Inventory WHERE ID=@procID
CREATE PROC sp_updateRecord @procID int, @procName varchar(20), @procType
varchar(20) AS UPDATE Inventory SET name=@procName, type=@procType where ID=@procID
--- Insert records into the Inventory table
EXE sp_insertRecord 4, 'ER Vol 1', 'DVD'
EXE sp_insertRecord 5, 'ER', 'VHS'
EXE sp_insertRecord 6, 'Sixth Sense', 'DVD'
--- Delete record with ID=3
EXEC sp_deleteRecord 3
--- Update record with ID=5
EXEC sp-updateRecord 5 'ERVol1', 'VHS'
--- View the updated table
EXEC sp_getRecords
GO

//////////////////////////////////////////////////////////////////////////////////////////////////

I got the following error messages:
Msg 111, Level 15, State 1, Procedure sp_getRecords, Line 8
'CREATE/ALTER PROCEDURE' must be the first statement in a query batch.
Msg 156, Level 15, State 1, Procedure sp_getRecords, Line 10
Incorrect syntax near the keyword 'PROC'.
Msg 156, Level 15, State 1, Procedure sp_getRecords, Line 11
Incorrect syntax near the keyword 'PROC'.
Msg 102, Level 15, State 1, Procedure sp_getRecords, Line 14
Incorrect syntax near 'EXE'.
Msg 102, Level 15, State 1, Procedure sp_getRecords, Line 20
Incorrect syntax near 'updateRecord'.
/////////////////////////////////////////////////////////////////////////////////////////////////////
Please help, tell me what is wrong in my execution of the code and advise me how I can correct this problem.
Thanks,
Scott Chang

View 1 Replies View Related

SSMS-EE: Creating And Using Stored Procedures - Error Messages 111, 156, &&amp; 102

May 11, 2006



Hi all,

I tried to use the SQL Server Managemet Studio-Express Edition to execute the following code statements:

--- SQLQuery.sql---

USE testDB
DECLARE @procID int
DECLARE @procName varchar(20)
DECLARE @procType varchar(20)
CREATE PROC sp_getRecords AS SELECT * FROM Inventory
CREATE PROC sp_insertRecord @procID int, @procName varchar(20), @procType
varchar(20) AS INSERT INTO Inventory VALUES (@procID, @procName, @procType)
CREATE PROC sp_deleteRecord @procID int AS DELETE FROM Inventory WHERE ID=@procID
CREATE PROC sp_updateRecord @procID int, @procName varchar(20), @procType
varchar(20) AS UPDATE Inventory SET name=@procName, type=@procType where ID=@procID
--- Insert records into the Inventory table
EXE sp_insertRecord 4, 'ER Vol 1', 'DVD'
EXE sp_insertRecord 5, 'ER', 'VHS'
EXE sp_insertRecord 6, 'Sixth Sense', 'DVD'
--- Delete record with ID=3
EXEC sp_deleteRecord 3
--- Update record with ID=5
EXEC sp-updateRecord 5 'ERVol1', 'VHS'
--- View the updated table
EXEC sp_getRecords
GO

//////////////////////////////////////////////////////////////////////////////////////////////////

I got the following T-SQL error messages:
Msg 111, Level 15, State 1, Procedure sp_getRecords, Line 8
'CREATE/ALTER PROCEDURE' must be the first statement in a query batch.
Msg 156, Level 15, State 1, Procedure sp_getRecords, Line 10
Incorrect syntax near the keyword 'PROC'.
Msg 156, Level 15, State 1, Procedure sp_getRecords, Line 11
Incorrect syntax near the keyword 'PROC'.
Msg 102, Level 15, State 1, Procedure sp_getRecords, Line 14
Incorrect syntax near 'EXE'.
Msg 102, Level 15, State 1, Procedure sp_getRecords, Line 20
Incorrect syntax near 'updateRecord'.
/////////////////////////////////////////////////////////////////////////////////////////////////////
Please help, tell me what is wrong in my execution of the code and advise me how I can correct this problem.
Thanks,
Scott Chang

View 6 Replies View Related

SSMS-EE: Creating And Using Stored Procedures - Error Messages 111, 156, &&amp; 102

May 10, 2006

Hi all,

I tried to use the SSMS-EE Query to execute the following code statements:

--- SQLQuery.sql---

USE testDB
DECLARE @procID int
DECLARE @procName varchar(20)
DECLARE @procType varchar(20)
CREATE PROC sp_getRecords AS SELECT * FROM Inventory
CREATE PROC sp_insertRecord @procID int, @procName varchar(20), @procType
varchar(20) AS INSERT INTO Inventory VALUES (@procID, @procName, @procType)
CREATE PROC sp_deleteRecord @procID int AS DELETE FROM Inventory WHERE ID=@procID
CREATE PROC sp_updateRecord @procID int, @procName varchar(20), @procType
varchar(20) AS UPDATE Inventory SET name=@procName, type=@procType where ID=@procID
--- Insert records into the Inventory table
EXE sp_insertRecord 4, 'ER Vol 1', 'DVD'
EXE sp_insertRecord 5, 'ER', 'VHS'
EXE sp_insertRecord 6, 'Sixth Sense', 'DVD'
--- Delete record with ID=3
EXEC sp_deleteRecord 3
--- Update record with ID=5
EXEC sp-updateRecord 5 'ERVol1', 'VHS'
--- View the updated table
EXEC sp_getRecords
GO

//////////////////////////////////////////////////////////////////////////////////////////////////

I got the following error messages:
Msg 111, Level 15, State 1, Procedure sp_getRecords, Line 8
'CREATE/ALTER PROCEDURE' must be the first statement in a query batch.
Msg 156, Level 15, State 1, Procedure sp_getRecords, Line 10
Incorrect syntax near the keyword 'PROC'.
Msg 156, Level 15, State 1, Procedure sp_getRecords, Line 11
Incorrect syntax near the keyword 'PROC'.
Msg 102, Level 15, State 1, Procedure sp_getRecords, Line 14
Incorrect syntax near 'EXE'.
Msg 102, Level 15, State 1, Procedure sp_getRecords, Line 20
Incorrect syntax near 'updateRecord'.
/////////////////////////////////////////////////////////////////////////////////////////////////////
Please help, tell me what is wrong in my execution of the code and advise me how I can correct this problem.
Thanks,
Scott Chang

View 1 Replies View Related

SSMS-EE: Creating And Using Stored Procedures - Error Messages 111, 156, &&amp; 102

May 11, 2006



Hi all,

I tried to use the SQL Server Managemet Studio-Express Edition to execute the following code statements:

--- SQLQuery.sql---

USE testDB
DECLARE @procID int
DECLARE @procName varchar(20)
DECLARE @procType varchar(20)
CREATE PROC sp_getRecords AS SELECT * FROM Inventory
CREATE PROC sp_insertRecord @procID int, @procName varchar(20), @procType
varchar(20) AS INSERT INTO Inventory VALUES (@procID, @procName, @procType)
CREATE PROC sp_deleteRecord @procID int AS DELETE FROM Inventory WHERE ID=@procID
CREATE PROC sp_updateRecord @procID int, @procName varchar(20), @procType
varchar(20) AS UPDATE Inventory SET name=@procName, type=@procType where ID=@procID
--- Insert records into the Inventory table
EXE sp_insertRecord 4, 'ER Vol 1', 'DVD'
EXE sp_insertRecord 5, 'ER', 'VHS'
EXE sp_insertRecord 6, 'Sixth Sense', 'DVD'
--- Delete record with ID=3
EXEC sp_deleteRecord 3
--- Update record with ID=5
EXEC sp-updateRecord 5 'ERVol1', 'VHS'
--- View the updated table
EXEC sp_getRecords
GO

//////////////////////////////////////////////////////////////////////////////////////////////////

I got the following T-SQL error messages:
Msg 111, Level 15, State 1, Procedure sp_getRecords, Line 8
'CREATE/ALTER PROCEDURE' must be the first statement in a query batch.
Msg 156, Level 15, State 1, Procedure sp_getRecords, Line 10
Incorrect syntax near the keyword 'PROC'.
Msg 156, Level 15, State 1, Procedure sp_getRecords, Line 11
Incorrect syntax near the keyword 'PROC'.
Msg 102, Level 15, State 1, Procedure sp_getRecords, Line 14
Incorrect syntax near 'EXE'.
Msg 102, Level 15, State 1, Procedure sp_getRecords, Line 20
Incorrect syntax near 'updateRecord'.
/////////////////////////////////////////////////////////////////////////////////////////////////////
Please help, tell me what is wrong in my execution of the code and advise me how I can correct this problem.
Thanks,
Scott Chang

View 3 Replies View Related

SSMS-EE: Creating And Using Stored Procedures - T-SQL Error Messages 111, 156, &&amp; 102

May 10, 2006

Hi all,

I tried to use the SQL Server Management Studio-Express Edition to execute the following code statements:

--- SQLQuery.sql---

USE testDB
DECLARE @procID int
DECLARE @procName varchar(20)
DECLARE @procType varchar(20)
CREATE PROC sp_getRecords AS SELECT * FROM Inventory
CREATE PROC sp_insertRecord @procID int, @procName varchar(20), @procType
varchar(20) AS INSERT INTO Inventory VALUES (@procID, @procName, @procType)
CREATE PROC sp_deleteRecord @procID int AS DELETE FROM Inventory WHERE ID=@procID
CREATE PROC sp_updateRecord @procID int, @procName varchar(20), @procType
varchar(20) AS UPDATE Inventory SET name=@procName, type=@procType where ID=@procID
--- Insert records into the Inventory table
EXE sp_insertRecord 4, 'ER Vol 1', 'DVD'
EXE sp_insertRecord 5, 'ER', 'VHS'
EXE sp_insertRecord 6, 'Sixth Sense', 'DVD'
--- Delete record with ID=3
EXEC sp_deleteRecord 3
--- Update record with ID=5
EXEC sp-updateRecord 5 'ERVol1', 'VHS'
--- View the updated table
EXEC sp_getRecords
GO

//////////////////////////////////////////////////////////////////////////////////////////////////

I got the following T-SQL error messages:
Msg 111, Level 15, State 1, Procedure sp_getRecords, Line 8
'CREATE/ALTER PROCEDURE' must be the first statement in a query batch.
Msg 156, Level 15, State 1, Procedure sp_getRecords, Line 10
Incorrect syntax near the keyword 'PROC'.
Msg 156, Level 15, State 1, Procedure sp_getRecords, Line 11
Incorrect syntax near the keyword 'PROC'.
Msg 102, Level 15, State 1, Procedure sp_getRecords, Line 14
Incorrect syntax near 'EXE'.
Msg 102, Level 15, State 1, Procedure sp_getRecords, Line 20
Incorrect syntax near 'updateRecord'.
/////////////////////////////////////////////////////////////////////////////////////////////////////
Please help, tell me what is wrong in my execution of the code and advise me how I can correct this problem.
Thanks,
Scott Chang

View 3 Replies View Related

SSMS-EE: Creating And Using Stored Procedures - Error Messages 111, 156, &&amp; 102

May 10, 2006



Hi all,

I tried to use the SQL Server Managemet Studio-Express Edition to execute the following code statements:

--- SQLQuery.sql---

USE testDB
DECLARE @procID int
DECLARE @procName varchar(20)
DECLARE @procType varchar(20)
CREATE PROC sp_getRecords AS SELECT * FROM Inventory
CREATE PROC sp_insertRecord @procID int, @procName varchar(20), @procType
varchar(20) AS INSERT INTO Inventory VALUES (@procID, @procName, @procType)
CREATE PROC sp_deleteRecord @procID int AS DELETE FROM Inventory WHERE ID=@procID
CREATE PROC sp_updateRecord @procID int, @procName varchar(20), @procType
varchar(20) AS UPDATE Inventory SET name=@procName, type=@procType where ID=@procID
--- Insert records into the Inventory table
EXE sp_insertRecord 4, 'ER Vol 1', 'DVD'
EXE sp_insertRecord 5, 'ER', 'VHS'
EXE sp_insertRecord 6, 'Sixth Sense', 'DVD'
--- Delete record with ID=3
EXEC sp_deleteRecord 3
--- Update record with ID=5
EXEC sp-updateRecord 5 'ERVol1', 'VHS'
--- View the updated table
EXEC sp_getRecords
GO

//////////////////////////////////////////////////////////////////////////////////////////////////

I got the following T-SQL error messages:
Msg 111, Level 15, State 1, Procedure sp_getRecords, Line 8
'CREATE/ALTER PROCEDURE' must be the first statement in a query batch.
Msg 156, Level 15, State 1, Procedure sp_getRecords, Line 10
Incorrect syntax near the keyword 'PROC'.
Msg 156, Level 15, State 1, Procedure sp_getRecords, Line 11
Incorrect syntax near the keyword 'PROC'.
Msg 102, Level 15, State 1, Procedure sp_getRecords, Line 14
Incorrect syntax near 'EXE'.
Msg 102, Level 15, State 1, Procedure sp_getRecords, Line 20
Incorrect syntax near 'updateRecord'.
/////////////////////////////////////////////////////////////////////////////////////////////////////
Please help, tell me what is wrong in my execution of the code and advise me how I can correct this problem.
Thanks,
Scott Chang

View 1 Replies View Related

T-SQL (SS2K8) :: Search Based On Table Name And Add Code To Existing Stored Procedures

Jun 30, 2014

Below is sample SQL:

SQL_1: Creates a database
SQL_2: Creates 2 stored procedures

Now, I need to search database SP`s for Table2 t2 ON t2.CID = t1.CID and ALTER them with Table2 t2 ON t2.CID = t1.CID.

INNER JOIN Table3 t3 ON t3.CID = t1.CID
WHERE CustGroup = 'Employees'SQL_1:
USE [master]
GO

[code]...

View 6 Replies View Related

MSSQL 7 Replication - Creating Of Standard Sp_MS... Stored Procedures

Aug 15, 2001

I am running MS SQL Server 7 with SP3 installed and am having some problems getting replication to work correctly. I want to replicate all tables from one database to another database on the same server. I can setup replication, add publications and add subscriptions without any problem and all goes well until the replication process starts when the job aborts because it cannot find the sp_MSins..., sp_MSupd... or the sp_MSdel... stored procedures. I have used the New Publication wizard to create a Transactional publication, published all tables and allowed the wizard to use the default stored procedures which it says will be created when the subscribers are initialized but although I have created push subcriptions the stored procedures are never created and hence the replication fails whenever the job runs.

I have SA access to the databases concerned and as far as I am aware the jobs are running as my login - can anybody help me out as this is beginning to drive me nuts.

Thanks

Chris

View 1 Replies View Related

Creating CSV Files Using BCP &&amp; Stored Procedures:BCP Executed From T-SQL Using Xp_cmdshell-How To Declare The Scalar Variable @@

Jan 24, 2008

Hi all,

I tried to create a CSV file using Bulk Copy Program (BCP) and Stored Procedures: BCP executed from T-SQL using xp_cmdshell. I have the following sql code executed in my SQL Server Management Studio Express and error message:


--scBCPcLabResults.sql--

declare @sql varchar(8000)
select @sql = 'bcp ChDbLabResults out
c:cpChDbLabResults.txt -c -t, -T -S' + @@.SQLEXPRESS
exec master..xp_cmdshell @sql

Msg 137, Level 15, State 2, Line 3
Must declare the scalar variable "@@".

=========================================================================================
--scBCPcLabResults.sql--

declare @sql varchar(8000)
select @sql = 'bcp ChDbLabResults out
c:cpChDbLabResults.txt -c -t, -T -S' + @@SQLEXPRESS
exec master..xp_cmdshell @sql

Msg 137, Level 15, State 2, Line 3
Must declare the scalar variable "@@SQLEXPRESS".

===================================================================

I copied this set of code from a tutorial article that says "@@servername". My Sql Server is SQLEXPRESS, so I put @@.SQLEXPRESS or @@SQLEXPRESS in the code of scBCPcLabResults.sql.
I do not know why I got an error {Must declare the scalar variable "@@"} or {Must declare the scalar variable "@@SQLEXPRESS"}!!!??? Please help and advise me how to solve this problem.

Thanks in advance,
Scott Chang

View 3 Replies View Related

Can SSRS 2005 Handle Stored Procedures Or SQL Subqueries That Rreturn Rowsets Based On Multiple SQL Updates?

Nov 8, 2006

Hello,

I have a stored procedure that creates a temporary table, and then populates it using an INSERT and then a series of UPDATE statements. The procedure then returns the temporary table which will contain data in all of its columns.

When I call this procedure from SSRS 2005, the rowset returned contains data in only those columns that are populated by the INSERT statement. The columns that are set via the UPDATE statements are all empty. I read (in the Hitchhikers Guide to Reporting Services) that SSRS will only process the first rowset in a stored procedure that generates multiple rowsets. Is this true? Is this why SSRS does not retrieve data for the columns that are populated by the UPDATE statements?

Here is the stored procedure:

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

-- File: sp_GetProgramsWatchedByDateRange.sql
-- Desc: Returns EDP program and related channel (i.e., provider) information from the IPTV Data warehouse.
-- Note that some of that data used by this procedure are obtained from the RMS_EPG database
-- which is created by an application (loadEPG) that loads the EPG data from a GLF format XML file.
-- Auth: H Hunsaker
-- Date: 11/07/2006

-- Example invocation
-- EXEC dbo.sp_GetProgramsWatchedByDateRange ...

-- Arguments/Parameters:

-- Parameter Name Type Description
-- 3. StartDate datetime First date of reporting period
-- 4. EndDate datetime Last date of reporting period
-- TerseMode bit Return all columns? (1 = no, 0 = yes)
-- 5. AsXML bit Resultset format (0 = standard, 1 = XML)
-- 6. Debug bit Debug mode (0 = off, 1 = on). Currently disabled

IF OBJECT_ID (N'dbo.sp_GetProgramsWatchedByDateRange') IS NOT NULL
DROP PROCEDURE dbo.sp_GetProgramsWatchedByDateRange
GO

CREATE PROCEDURE dbo.sp_GetProgramsWatchedByDateRange
@StartDate datetime = NULL,
@EndDate datetime = NULL,
@TerseMode bit = 0,
@AsXML bit = 0,
@Debug bit = 0
AS
-- Notes: Much of the program content (roles, flags, etc.) that we want is not stored in the IPTV data warehouse.
-- So I am going to the RMS_EPG database to obtain that information.
-- We will have to ensure that the 2 databases are generated at the same or a matching time
-- in order to to ensure that all programID values in the data warehouse can be located in the RMS_EPG database.

-- Debug code for testing
-- DECLARE @StartDate datetime
-- DECLARE @EndDate datetime
-- DECLARE @TerseMode bit

--SET @StartDate = NULL
--SET @EndDate = NULL
--SET @TerseMode = 1

SET NOCOUNT ON

CREATE TABLE #programWatched
(
--IPTV device ID
tdeviceId uniqueidentifier NULL,
taccountId uniqueidentifier NULL,

-- Basic program information
tprogram int NULL, -- programID from EPG XML, needed to access program data in the RMS_EPG db.
tprogramId uniqueidentifier NULL, -- programID generated by IPTV
tprogramTitle varchar(150) NULL,
tprogramEpisodeTitle varchar(100) NULL,
tprogramDescription varchar(500) NULL,

toriginDateTime datetime NULL,
tduration bigint NULL,
tprogramType nvarchar(100) NULL,
tchannelCallName nvarchar(20) NULL,

--Rating
programMPAARating varchar(50) NULL,
programVCHIPRating varchar(50) NULL,
programMPAARatingVal smallint NULL,
programVChipRatingVal smallint NULL,

-- Categories
programGenre varchar(50) NULL,
programCategory1 varchar(50) NULL,
programCategory2 varchar(50) NULL,
programCategory3 varchar(50) NULL,
programCategory4 varchar(50) NULL,

-- Roles
programActor1FirstName varchar(50) NULL,
programActor1LastName varchar(50) NULL,
programActor1 varchar(100) NULL,

programActor2FirstName varchar(50) NULL,
programActor2LastName varchar(50) NULL,
programActor2 varchar(100) NULL,

programActor3FirstName varchar(50) NULL,
programActor3LastName varchar(50) NULL,
programActor3 varchar(100) NULL,

programActor4FirstName varchar(50) NULL,
programActor4LastName varchar(50) NULL,
programActor4 varchar(100) NULL,

programActor5FirstName varchar(50) NULL,
programActor5LastName varchar(50) NULL,
programActor5 varchar(100) NULL,

programActor6FirstName varchar(50) NULL,
programActor6LastName varchar(50) NULL,
programActor6 varchar(100) NULL,

programActor7FirstName varchar(50) NULL,
programActor7LastName varchar(50) NULL,
programActor7 varchar(100) NULL,

programActor8FirstName varchar(50) NULL,
programActor8LastName varchar(50) NULL,
programActor8 varchar(100) NULL,

programDirectorFirstName varchar(50) NULL,
programDirectorLastName varchar(50) NULL,
programDirector varchar(100) NULL,

programWriterFirstName varchar(50) NULL,
programWriterLastName varchar(50) NULL,
programWriter varchar(100) NULL,

programProducerFirstName varchar(50) NULL,
programProducerLastName varchar(50) NULL,
programProducer varchar(100) NULL,

-- Flags
ClosedCaption bit NULL,
InStereo bit NULL,
Repeats bit NULL,
New bit NULL,
Live bit NULL,
Taped bit NULL,
Subtitled bit NULL,
SAP bit NULL,
ThreeD bit NULL,
Letterbox bit NULL,
HDTV bit NULL,
Dolby bit NULL,
DVS bit NULL,

FlagOrdinalValue smallint NULL,

-- Channel
tchannelId int NULL,

callLetters varchar(20) NULL,
displayName varchar(50) NULL,
type varchar(50) NULL,
networkAffiliation varchar(50) NULL
)

-- I store the program watching data in a temp table because
-- data from the VIL and the Sandbox that were used to test this procedure were either incomplete or invalid.
-- Use of a temp table with a series of updates allow me more control over the result set.

IF @StartDate IS NOT NULL AND @EndDate IS NOT NULL
INSERT INTO #programWatched (
tdeviceId,
tprogramId,
--tprogramTitle,
--tprogramEpisodeTitle,
toriginDateTime,
tduration,
--tprogramType,
--tchannelCallName,

ClosedCaption,
InStereo,
Repeats,
New,
Live,
Taped,
Subtitled,
SAP,
ThreeD,
Letterbox,
HDTV,
Dolby,
DVS
)
SELECT pw.DeviceID,
pw.programID,
--epg.program,
--epg.programTitle,
--epg.programEpisodeTitle,
pw.originTime AS 'When Watched',
pw.Duration AS 'Duration Seconds',
--epg.programType,
--epg.channelCallName,

0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -- program flag values default to zero, as we do not want NULL values.

FROM DW_EventClientProgramWatched pw
WHERE programID IS NOT NULL AND programID != '00000000-0000-0000-0000-000000000000' -- These values should not occur, but they did in the test system
AND originTime BETWEEN @StartDate AND @EndDate
ELSE
INSERT INTO #programWatched (
tdeviceId,
tprogramId,
--tprogramTitle,
--tprogramEpisodeTitle,
toriginDateTime,
tduration,
--tprogramType,
--tchannelCallName,

ClosedCaption,
InStereo,
Repeats,
New,
Live,
Taped,
Subtitled,
SAP,
ThreeD,
Letterbox,
HDTV,
Dolby,
DVS
)
SELECT pw.DeviceID,
pw.programID,
--epg.program,
--epg.programTitle,
--epg.programEpisodeTitle,
pw.originTime AS 'When Watched',
pw.Duration AS 'Duration Seconds',
--epg.programType,
--epg.channelCallName,

0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -- program flag values default to zero, as we do not want NULL values.

FROM DW_EventClientProgramWatched pw
WHERE programID IS NOT NULL AND programID != '00000000-0000-0000-0000-000000000000' -- These values should not occur, but they did in the test system

-- AccountId/SubscriberId
UPDATE #programWatched
SET taccountId = (SELECT accountId
FROM DW_BRDB_bm_device d
WHERE d.deviceId = tdeviceId)

-- program (this is the integer program ID stored in the EPG XML, not to be confused with the IPTV programId)
-- a program can occur on multiple channels, so we filter channels where scheduleTime <= originTime <= scheculeTime + durationSecs
UPDATE #programWatched
SET tchannelCallName = (SELECT TOP 1 channelCallName
FROM DW_EPG EPG
WHERE tprogramId = EPG.programId AND toriginDateTime BETWEEN scheduleTime AND DATEADD(s, epg.durationSecs, epg.scheduleTime))

UPDATE #programWatched
SET tprogram = (SELECT TOP 1 program FROM DW_EPG EPG WHERE tprogramId = EPG.programId AND tchannelCallName = channelCallName),
tprogramTitle = (SELECT TOP 1 programTitle FROM DW_EPG EPG WHERE tprogramId = EPG.programId AND tchannelCallName = channelCallName),
tprogramEpisodeTitle = (SELECT TOP 1 programEpisodeTitle FROM DW_EPG EPG WHERE tprogramId = EPG.programId AND tchannelCallName = channelCallName),
tprogramType = (SELECT TOP 1 programType FROM DW_EPG EPG WHERE tprogramId = EPG.programId AND tchannelCallName = channelCallName)

-- Rating (otained from programValues, can also be obtained from programFlags)
UPDATE #programWatched
SET programMPAARating = (SELECT TOP 1 programValue
FROM RMS_EPG..programValue pv
WHERE tprogram = pv.programID AND pv.programValueTypeId = 9)

UPDATE #programWatched
SET programMPAARatingVal = CASE programMPAARating
WHEN 'G' THEN 10
WHEN 'PG' THEN 25
WHEN 'PG-13' THEN 30
WHEN 'R' THEN 35
WHEN 'NC-17' THEN 50
WHEN 'NRAO' THEN 60
WHEN 'NR' THEN 0
ELSE 0
END

UPDATE #programWatched
SET programVChipRating = (SELECT TOP 1 programValue
FROM RMS_EPG..programValue pv
WHERE tprogram = pv.programID AND pv.programValueTypeId = 8)

UPDATE #programWatched
SET programVChipRatingVal = CASE programVChipRating
WHEN 'TV-Y' THEN 10
WHEN 'TV-Y7' THEN 20
WHEN 'TV-G' THEN 35
WHEN 'TV-PG' THEN 40
WHEN 'TV-14' THEN 45
WHEN 'TV-MA' THEN 60
ELSE 0
END

-- Genre
UPDATE #programWatched
SET programGenre = (SELECT TOP 1 programCategoryTypeValue
FROM RMS_EPG..programCategory pc
INNER JOIN RMS_EPG..programSubCategoryType psct ON psct.programSubCategoryTypeId = pc.programCategoryId
INNER JOIN RMS_EPG..programCategoryType pct ON pct.programCategoryTypeId = psct.programCategoryTypeId
WHERE tprogram = pc.programID)

-- Categories
UPDATE #programWatched
SET programCategory1 = (SELECT TOP 1 programSubCategoryTypeValue
FROM RMS_EPG..programCategory pc
INNER JOIN RMS_EPG..programSubCategoryType pct ON pct.programSubCategoryTypeId = pc.programCategoryId
WHERE tprogram = pc.programID)

UPDATE #programWatched
SET programCategory2 = (SELECT TOP 1 programSubCategoryTypeValue
FROM RMS_EPG..programCategory pc
INNER JOIN RMS_EPG..programSubCategoryType pct ON pct.programSubCategoryTypeId = pc.programCategoryId
WHERE tprogram = pc.programID AND programSubCategoryTypeValue NOT IN (programCategory1))

UPDATE #programWatched
SET programCategory3 = (SELECT TOP 1 programSubCategoryTypeValue
FROM RMS_EPG..programCategory pc
INNER JOIN RMS_EPG..programSubCategoryType pct ON pct.programSubCategoryTypeId = pc.programCategoryId
WHERE tprogram = pc.programID AND programSubCategoryTypeValue NOT IN (programCategory1, programCategory2))

UPDATE #programWatched
SET programCategory4 = (SELECT TOP 1 programSubCategoryTypeValue
FROM RMS_EPG..programCategory pc
INNER JOIN RMS_EPG..programSubCategoryType pct ON pct.programSubCategoryTypeId = pc.programCategoryId
WHERE tprogram = pc.programID AND programSubCategoryTypeValue NOT IN (programCategory1, programCategory2, programCategory3))

-- Roles
UPDATE #programWatched
SET programDirectorFirstName = (SELECT TOP 1 programRoleFirstName
FROM RMS_EPG..programRoleName prn
INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
WHERE tprogram = pr.programID AND pr.programRoleTypeId = 2)

UPDATE #programWatched
SET programDirectorLastName = (SELECT TOP 1 programRoleLastName
FROM RMS_EPG..programRoleName prn
INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
WHERE tprogram = pr.programID AND pr.programRoleTypeId = 2)

UPDATE #programWatched
SET programDirector = programDirectorLastName + ' , ' + programDirectorFirstName

UPDATE #programWatched
SET programWriterFirstName = (SELECT TOP 1 programRoleFirstName
FROM RMS_EPG..programRoleName prn
INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
WHERE tprogram = pr.programID AND pr.programRoleTypeId = 7)

UPDATE #programWatched
SET programWriterLastName = (SELECT TOP 1 programRoleLastName
FROM RMS_EPG..programRoleName prn
INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
WHERE tprogram = pr.programID AND pr.programRoleTypeId = 7)

UPDATE #programWatched
SET programWriter = programWriterLastName + ' , ' + programWriterFirstName

UPDATE #programWatched
SET programProducerFirstName = (SELECT TOP 1 programRoleFirstName
FROM RMS_EPG..programRoleName prn
INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
WHERE tprogram = pr.programID AND pr.programRoleTypeId = 6)

UPDATE #programWatched
SET programProducerLastName = (SELECT TOP 1 programRoleLastName
FROM RMS_EPG..programRoleName prn
INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
WHERE tprogram = pr.programID AND pr.programRoleTypeId = 6)

UPDATE #programWatched
SET programProducer = programProducerLastName + ' , ' + programProducerFirstName

UPDATE #programWatched
SET programActor1FirstName = (SELECT TOP 1 programRoleFirstName
FROM RMS_EPG..programRoleName prn
INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
WHERE tprogram = pr.programID AND pr.programRoleTypeId = 1)
UPDATE #programWatched
SET programActor1LastName = (SELECT TOP 1 programRoleLastName
FROM RMS_EPG..programRoleName prn
INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
WHERE tprogram = pr.programID AND pr.programRoleTypeId = 1)

UPDATE #programWatched
SET programActor1 = programActor1LastName + ' , ' + programActor1FirstName

UPDATE #programWatched
SET programActor2FirstName = (SELECT TOP 1 programRoleFirstName
FROM RMS_EPG..programRoleName prn
INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
WHERE tprogram = pr.programID AND pr.programRoleTypeId = 1
AND programRoleFirstName NOT IN (programActor1FirstName) AND programRoleLastName NOT IN (programActor1LastName))

UPDATE #programWatched
SET programActor2LastName = (SELECT TOP 1 programRoleLastName
FROM RMS_EPG..programRoleName prn
INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
WHERE tprogram = pr.programID AND pr.programRoleTypeId = 1
AND programRoleLastName NOT IN (programActor1LastName) AND programRoleLastName NOT IN (programActor1LastName))

UPDATE #programWatched
SET programActor2 = programActor2LastName + ' , ' + programActor2FirstName

UPDATE #programWatched
SET programActor3FirstName = (SELECT TOP 1 programRoleFirstName
FROM RMS_EPG..programRoleName prn
INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
WHERE tprogram = pr.programID AND pr.programRoleTypeId = 1
AND programRoleFirstName NOT IN (programActor1FirstName) AND programRoleLastName NOT IN (programActor1LastName)
AND programRoleFirstName NOT IN (programActor2FirstName) AND programRoleLastName NOT IN (programActor2LastName))

UPDATE #programWatched
SET programActor3LastName = (SELECT TOP 1 programRoleLastName
FROM RMS_EPG..programRoleName prn
INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
WHERE tprogram = pr.programID AND pr.programRoleTypeId = 1
AND programRoleLastName NOT IN (programActor1LastName) AND programRoleLastName NOT IN (programActor1LastName)
AND programRoleLastName NOT IN (programActor2LastName) AND programRoleLastName NOT IN (programActor2LastName))

UPDATE #programWatched
SET programActor3 = programActor3LastName + ' , ' + programActor3FirstName

UPDATE #programWatched
SET programActor4FirstName = (SELECT TOP 1 programRoleFirstName
FROM RMS_EPG..programRoleName prn
INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
WHERE tprogram = pr.programID AND pr.programRoleTypeId = 1
AND programRoleFirstName NOT IN (programActor1FirstName) AND programRoleLastName NOT IN (programActor1LastName)
AND programRoleFirstName NOT IN (programActor2FirstName) AND programRoleLastName NOT IN (programActor2LastName)
AND programRoleFirstName NOT IN (programActor3FirstName) AND programRoleLastName NOT IN (programActor3LastName))

UPDATE #programWatched
SET programActor4LastName = (SELECT TOP 1 programRoleLastName
FROM RMS_EPG..programRoleName prn
INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
WHERE tprogram = pr.programID AND pr.programRoleTypeId = 1
AND programRoleFirstName NOT IN (programActor1FirstName) AND programRoleLastName NOT IN (programActor1LastName)
AND programRoleFirstName NOT IN (programActor2FirstName) AND programRoleLastName NOT IN (programActor2LastName)
AND programRoleFirstName NOT IN (programActor3FirstName) AND programRoleLastName NOT IN (programActor3LastName))

UPDATE #programWatched
SET programActor4 = programActor4LastName + ' , ' + programActor4FirstName

UPDATE #programWatched
SET programActor5FirstName = (SELECT TOP 1 programRoleFirstName
FROM RMS_EPG..programRoleName prn
INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
WHERE tprogram = pr.programID AND pr.programRoleTypeId = 1
AND programRoleFirstName NOT IN (programActor1FirstName) AND programRoleLastName NOT IN (programActor1LastName)
AND programRoleFirstName NOT IN (programActor2FirstName) AND programRoleLastName NOT IN (programActor2LastName)
AND programRoleFirstName NOT IN (programActor3FirstName) AND programRoleLastName NOT IN (programActor3LastName)
AND programRoleFirstName NOT IN (programActor4FirstName) AND programRoleLastName NOT IN (programActor4LastName))

UPDATE #programWatched
SET programActor5LastName = (SELECT TOP 1 programRoleLastName
FROM RMS_EPG..programRoleName prn
INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
WHERE tprogram = pr.programID AND pr.programRoleTypeId = 1
AND programRoleFirstName NOT IN (programActor1FirstName) AND programRoleLastName NOT IN (programActor1LastName)
AND programRoleFirstName NOT IN (programActor2FirstName) AND programRoleLastName NOT IN (programActor2LastName)
AND programRoleFirstName NOT IN (programActor3FirstName) AND programRoleLastName NOT IN (programActor3LastName)
AND programRoleFirstName NOT IN (programActor4FirstName) AND programRoleLastName NOT IN (programActor4LastName))


UPDATE #programWatched
SET programActor5 = programActor5LastName + ' , ' + programActor5FirstName

UPDATE #programWatched
SET programActor6FirstName = (SELECT TOP 1 programRoleFirstName
FROM RMS_EPG..programRoleName prn
INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
WHERE tprogram = pr.programID AND pr.programRoleTypeId = 1
AND programRoleFirstName NOT IN (programActor1FirstName) AND programRoleLastName NOT IN (programActor1LastName)
AND programRoleFirstName NOT IN (programActor2FirstName) AND programRoleLastName NOT IN (programActor2LastName)
AND programRoleFirstName NOT IN (programActor3FirstName) AND programRoleLastName NOT IN (programActor3LastName)
AND programRoleFirstName NOT IN (programActor4FirstName) AND programRoleLastName NOT IN (programActor4LastName)
AND programRoleFirstName NOT IN (programActor5FirstName) AND programRoleLastName NOT IN (programActor5LastName))

UPDATE #programWatched
SET programActor6LastName = (SELECT TOP 1 programRoleLastName
FROM RMS_EPG..programRoleName prn
INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
WHERE tprogram = pr.programID AND pr.programRoleTypeId = 1
AND programRoleFirstName NOT IN (programActor1FirstName) AND programRoleLastName NOT IN (programActor1LastName)
AND programRoleFirstName NOT IN (programActor2FirstName) AND programRoleLastName NOT IN (programActor2LastName)
AND programRoleFirstName NOT IN (programActor3FirstName) AND programRoleLastName NOT IN (programActor3LastName)
AND programRoleFirstName NOT IN (programActor4FirstName) AND programRoleLastName NOT IN (programActor4LastName)
AND programRoleFirstName NOT IN (programActor5FirstName) AND programRoleLastName NOT IN (programActor5LastName))

UPDATE #programWatched
SET programActor6 = programActor6LastName + ' , ' + programActor6FirstName

UPDATE #programWatched
SET programActor7FirstName = (SELECT TOP 1 programRoleFirstName
FROM RMS_EPG..programRoleName prn
INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
WHERE tprogram = pr.programID AND pr.programRoleTypeId = 1
AND programRoleFirstName NOT IN (programActor1FirstName) AND programRoleLastName NOT IN (programActor1LastName)
AND programRoleFirstName NOT IN (programActor2FirstName) AND programRoleLastName NOT IN (programActor2LastName)
AND programRoleFirstName NOT IN (programActor3FirstName) AND programRoleLastName NOT IN (programActor3LastName)
AND programRoleFirstName NOT IN (programActor4FirstName) AND programRoleLastName NOT IN (programActor4LastName)
AND programRoleFirstName NOT IN (programActor5FirstName) AND programRoleLastName NOT IN (programActor5LastName)
AND programRoleFirstName NOT IN (programActor6FirstName) AND programRoleLastName NOT IN (programActor6LastName))

UPDATE #programWatched
SET programActor7LastName = (SELECT TOP 1 programRoleLastName
FROM RMS_EPG..programRoleName prn
INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
WHERE tprogram = pr.programID AND pr.programRoleTypeId = 1
AND programRoleFirstName NOT IN (programActor1FirstName) AND programRoleLastName NOT IN (programActor1LastName)
AND programRoleFirstName NOT IN (programActor2FirstName) AND programRoleLastName NOT IN (programActor2LastName)
AND programRoleFirstName NOT IN (programActor3FirstName) AND programRoleLastName NOT IN (programActor3LastName)
AND programRoleFirstName NOT IN (programActor4FirstName) AND programRoleLastName NOT IN (programActor4LastName)
AND programRoleFirstName NOT IN (programActor5FirstName) AND programRoleLastName NOT IN (programActor5LastName)
AND programRoleFirstName NOT IN (programActor6FirstName) AND programRoleLastName NOT IN (programActor6LastName))

UPDATE #programWatched
SET programActor7 = programActor7LastName + ' , ' + programActor7FirstName

UPDATE #programWatched
SET programActor8FirstName = (SELECT TOP 1 programRoleFirstName
FROM RMS_EPG..programRoleName prn
INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
WHERE tprogram = pr.programID AND pr.programRoleTypeId = 1
AND programRoleFirstName NOT IN (programActor1FirstName) AND programRoleLastName NOT IN (programActor1LastName)
AND programRoleFirstName NOT IN (programActor2FirstName) AND programRoleLastName NOT IN (programActor2LastName)
AND programRoleFirstName NOT IN (programActor3FirstName) AND programRoleLastName NOT IN (programActor3LastName)
AND programRoleFirstName NOT IN (programActor4FirstName) AND programRoleLastName NOT IN (programActor4LastName)
AND programRoleFirstName NOT IN (programActor5FirstName) AND programRoleLastName NOT IN (programActor5LastName)
AND programRoleFirstName NOT IN (programActor6FirstName) AND programRoleLastName NOT IN (programActor6LastName)
AND programRoleFirstName NOT IN (programActor7FirstName) AND programRoleLastName NOT IN (programActor7LastName))


UPDATE #programWatched
SET programActor8LastName = (SELECT TOP 1 programRoleLastName
FROM RMS_EPG..programRoleName prn
INNER JOIN RMS_EPG..programRole pr ON pr.programRoleNameId = prn.programRoleNameId
WHERE tprogram = pr.programID AND pr.programRoleTypeId = 1
AND programRoleFirstName NOT IN (programActor1FirstName) AND programRoleLastName NOT IN (programActor1LastName)
AND programRoleFirstName NOT IN (programActor2FirstName) AND programRoleLastName NOT IN (programActor2LastName)
AND programRoleFirstName NOT IN (programActor3FirstName) AND programRoleLastName NOT IN (programActor3LastName)
AND programRoleFirstName NOT IN (programActor4FirstName) AND programRoleLastName NOT IN (programActor4LastName)
AND programRoleFirstName NOT IN (programActor5FirstName) AND programRoleLastName NOT IN (programActor5LastName)
AND programRoleFirstName NOT IN (programActor6FirstName) AND programRoleLastName NOT IN (programActor6LastName)
AND programRoleFirstName NOT IN (programActor7FirstName) AND programRoleLastName NOT IN (programActor7LastName))

UPDATE #programWatched
SET programActor8 = programActor8LastName + ' , ' + programActor8FirstName

-- Channel (provider) Call Letters, Display Name and Type
-- Is this correct? Should we get the channelId from the schedule table?
-- Is this efficient? View execution plan

UPDATE #programWatched
SET tchannelId = (SELECT TOP 1 c.channelId
FROM RMS_EPG..channel c
INNER JOIN RMS_EPG..schedule s on s.channelID = c.channelID
WHERE s.programId = tprogram)

UPDATE #programWatched
SET callLetters = (SELECT TOP 1 c.channelCallLetters
FROM RMS_EPG..channel c
INNER JOIN RMS_EPG..schedule s on s.channelID = c.channelID
WHERE s.programId = tprogram and s.channelId = tchannelId)

UPDATE #programWatched
SET displayName = (SELECT TOP 1 c.channelDisplayName
FROM RMS_EPG..channel c
JOIN RMS_EPG..schedule s on s.channelID = c.channelID
WHERE s.programId = tprogram and s.channelId = tchannelId)

UPDATE #programWatched
SET type = (SELECT TOP 1 c.channelType
FROM RMS_EPG..channel c
INNER JOIN RMS_EPG..schedule s on s.channelID = c.channelID
WHERE s.programId = tprogram and s.channelId = tchannelId)

UPDATE #programWatched
SET networkAffiliation = (SELECT TOP 1 c.channelNetworkAffiliation
FROM RMS_EPG..channel c
INNER JOIN RMS_EPG..schedule s on s.channelID = c.channelID
WHERE s.programId = tprogram and s.channelId = tchannelId)

IF @TerseMode = 0
SELECT *
FROM #programWatched
ORDER BY toriginDateTime
ELSE
-- Get only Genre, title, show date/time, rating, call letters
SELECT tDeviceId, tprogramTitle, tprogramEpisodeTitle, programGenre, toriginDateTime, programMPAARating, programVCHIPRating, tchannelCallName
FROM #programWatched
ORDER BY toriginDateTime

DROP TABLE #programWatched

SET NOCOUNT OFF

GO

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

I also tried a query that populates some of its columns via subqueries. The query works fine when executed by the SQL Sevrer Query Analyzer,
meaning that all columns contain values, but when executed from SSRS, the columns that are poulated by the subqueries are empty, and only the columns that are not set by subqueries contain values:

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

SELECT PW.DeviceID,
PW.originTime AS 'When Watched',
PW.programID,
PW.Duration AS 'Duration Seconds',

(SELECT TOP 1 programTitle FROM DW_EPG WHERE DW_EPG.programId = PW.programId AND PW.originTime BETWEEN DW_EPG.scheduleTime
AND DATEADD(second, durationSecs, DW_EPG.scheduleTime)) AS Title,

(SELECT TOP 1 program FROM DW_EPG WHERE DW_EPG.programId = PW.programId AND PW.originTime BETWEEN DW_EPG.scheduleTime AND
DATEADD(second, durationSecs, DW_EPG.scheduleTime)) As program,

(SELECT TOP 1 programCategoryTypeValue
FROM RMS_EPG..programCategory PC
INNER JOIN RMS_EPG..programSubCategoryType PSCT ON psct.programSubCategoryTypeId = PC.programCategoryId
INNER JOIN RMS_EPG..programCategoryType PCT ON PCT.programCategoryTypeId = PSCT.programCategoryTypeId
WHERE PC.programID = (SELECT TOP 1 program FROM DW_EPG WHERE DW_EPG.programId = PW.programId AND PW.originTime BETWEEN
DW_EPG.scheduleTime AND DATEADD(second, durationSecs, DW_EPG.scheduleTime))) AS Genre,

(SELECT TOP 1 programSubCategoryTypeValue
FROM RMS_EPG..programCategory PC
INNER JOIN RMS_EPG..programSubCategoryType PSCT ON psct.programSubCategoryTypeId = PC.programCategoryId
INNER JOIN RMS_EPG..programCategoryType PCT ON PCT.programCategoryTypeId = PSCT.programCategoryTypeId
WHERE PC.programID = (SELECT TOP 1 program FROM DW_EPG WHERE DW_EPG.programId = PW.programId AND PW.originTime
BETWEEN DW_EPG.scheduleTime AND DATEADD(second, durationSecs, DW_EPG.scheduleTime))) AS Category

FROM DW_EventClientProgramWatched PW
ORDER BY DeviceId, programId, originTime

---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

Any help is appreciated

View 3 Replies View Related

Table Names In Stored Procedures As String Variables And Temporary Table Question

Apr 10, 2008

How do I use table names stored in variables in stored procedures?




Code Snippetif (select count(*) from @tablename) = 0 or (select count(*) from @tablename) = 1000000





I receive the error 'must declare table variable '@tablename''

I've looked into table variables and they are not what I would require to accomplish what is needed.
After browsing through the forums I believe I need to use dynamic sql particuarly involving sp_executesql. However, I am pretty new at sql and do not really understand how to use this and receive an output parameter from it(msdn kind of confuses me too). I am tryin got receive an integer count of the records from a certain table which can change to anything depending on what the user requires.




Code Snippet

if exists(Select * from sysobjects where name = @temptablename)
drop table @temptablename




It does not like the 'drop table @temptablename' part here. This probably wouldn't be an issue if I could get temporary tables to work, however when I use temporary tables i get invalid object '#temptable'.

Heres what the stored procedure does.
I duplicate a table that is going to be modified by using 'select into temptable'
I add the records required using 'Insert into temptable(Columns) Select(Columns)f rom TableA'
then I truncate the original table that is being modified and insert the temporary table into the original.

Heres the actual SQL query that produces the temporary table error.




Code Snippet
Select * into #temptableabcd from TableA

Insert into #temptableabcd(ColumnA, ColumnB,Field_01, Field_02)
SELECT ColumnA, ColumnB, Sum(ABC_01) as 'Field_01', Sum(ABC_02) as 'Field_02',
FROM TableB
where ColumnB = 003860
Group By ColumnA, ColumnB

TRUNCATE TABLE TableA

Insert into TableA(ColumnA, ColumnB,Field_01, Field_02)
Select ColumnA, ColumnB, Sum(Field_01) as 'Field_01', Sum('Field_02) as 'Field_02',
From #temptableabcd
Group by ColumnA, ColumnB




The above coding produces

Msg 208, Level 16, State 0, Line 1

Invalid object name '#temptableabcd'.

Why does this seem to work when I use an actual table? With an actual table the SQL runs smoothly, however that creates the table names as a variable problem from above. Is there certain limitation with temporary tables in stored procedures? How would I get the temporary table to work in this case if possible?

Thanks for the help.


View 6 Replies View Related







Copyrights 2005-15 www.BigResource.com, All rights reserved