Odd Stored Procedure error - syntax? - sql

I am trying to create a simple stored procedure in SQL Server 2005, and am puzzled by a syntax error I am getting.
Both tables have identical structure. tbl_Users_non_61 is empty and ready to receive the data.
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE Make_WEEKLY_SUMMARY
AS
BEGIN
SET NOCOUNT ON;
Select (tbl_Users.UserID
, tbl_Users.RegistrationType
, tbl_Users.Datecompleted)
INTO tbl_Users_non_61
FROM
SELECT tbl_Users.UserID
, tbl_Users.RegistrationType
, tbl_Users.Datecompleted
FROM tbl_Users;
END
GO
Resulting error:
Msg 102, Level 15, State 1, Procedure Make_WEEKLY_SUMMARY, Line 5
Incorrect syntax near ','.**

Since you just want to insert records into one table from another, there is a cleaner syntax:
INSERT INTO tbl_Users_non_61(UserId, RegistrationType, DateCompleted)
SELECT u.UserID, u.RegistrationType, u.Datecompleted
FROM tbl_Users AS u
To answer your question though, you do not need the ( ) around your first select, but you DO need them around your sub select, then you need to alias the sub-query you are referencing with the FROM:
Select t.UserID, t.RegistrationType, t.Datecompleted
INTO tbl_Users_non_61
FROM
(
SELECT u.UserID, u.RegistrationType, u.Datecompleted
FROM tbl_Users AS u
) as t;

Try this on:
SELECT
tbl_Users.UserID
, tbl_Users.RegistrationType
, tbl_Users.Datecompleted
INTO tbl_Users_non_61
FROM tbl_Users;
When you SELECT ... INTO, if the columns come from one table only, there's no need to SELECT those same columns again. Even if you had to take data from multiple columns, you still wouldn't need to reselect them, and perform a join instead.

Related

How to create a stored procedure to copy data from a query to a temporary table?

I have need of inserting data to a temporary table from an existing table/query. The following produces the error detailed below.
CREATE TABLE SPTemporary
AS
BEGIN
SELECT * into #temppT
FROM SampleTable
END
Throws this error:
Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'begin'.
Correct your syntax, use procedure instead of table :
create procedure SPTemporay
as
begin
select * into #temppT
from SampleTable
end
However, if you want only copy of data then only subquery is enough :
select st.* into #temppT
from SampleTable st
One method is:
select st.*
into SPTemporay
from SampleTable st
One select can only put data in one table. It is unclear which one you really want SPTemporary or #temppT. You can repeat the select if you really need the same data in two tables.
EDIT:
If you want a stored procedure, you could do:
create procedure SPTemporay
as begin
select *
into #temppT
from SampleTable
end;
This is rather non-sensical, because the temporary table is discarded when the stored procedure returns.
I think the syntax is wrong, it should be like that:
create table SPTemporay
as
select * from SampleTable
I hope this helps.

How to select query result inside stored procedure

I'm writing a stored procedure in SQL Server 2008 which contains a SELECT DISTINCT statement and another simple Select statement which is based on the result of first statement.
How to use the table returned by the SELECT DISTINCT statement i.e the UnitNumber column value in second Select statement?
Stored procedure:
CREATE PROCEDURE ExtractPacket
AS
BEGIN
SET NOCOUNT ON;
-- Select statements to check the number of unit
SELECT DISTINCT UnitNumber from dbo.CP_TemplateHandler
END
GO
you can create a temp table and fill it by first SELECT DISTINCT and then in second Select use that.
Excuse me for answer in order comment(i can comment yet :( )
I suggest that use First Select Distinct as a sub query of second Select Distinct query.

I am trying to run a query based on the results from a stored procedure

First, here is the code for sp_GetWorkQByUserName:
ALTER PROCEDURE [dbo].[sp_GetWorkQByUserName]
( #UserName varchar(50),
#StartDate datetime,
#EndDate datetime )
AS
BEGIN
SET NOCOUNT ON;
SELECT DISTINCT SpotId FROM tblSpotCount WHERE StoreNum = EXECUTE sp_GetUserLocationCodes(#UserName)
ORDER BY SpotDt ASC
END
I know my SELECT DISTINCT statement is wrong, but I wrote it like that to help show what I'm trying to do. I want to run this stored procedure based on the results from the sp_GetUserLocationCodes with a parameter of #UserName.
From what I can tell, my problem lies in how I'm calling sp_GetUserLocationCodes.
Question: how can I run a SELECT DISTINCT query on tblSpotCount.SpotId based on the results from the sp_GetUserLocationCodes stored procedure?
You cannot use a stored procedure directly in a query. You can, however, insert the results of a stored procedure into a temporary table and use that in your query:
CREATE TABLE #storeLocations
(
-- appropriate column names and data types go here
)
INSERT INTO #storeLocations (put column list here)
EXECUTE sp_GetUserLocationCodes(#UserName)
SELECT DISTINCT SpotId
FROM tblSpotCount
WHERE EXISTS (SELECT 1
FROM #storeLocations
WHERE #storeLocations.StoreNum = tblSpotCount.StoreNum)
ORDER BY SpotDt ASC
DROP TABLE #storeLocations

Linking a simple query to a script executing several stored procedures

Sorry I'm a bit new to this so just trying to get my head around linking everything up.
At the moment I have a normal query - SELECT FROM WHERE which basically finds about 2000 records that I need to update which link across several tables.
Can someone tell me how I can link this simple query to something else so I can basically execute several stored procedures, all in the same script? But only affecting the records returned by my simple query?
Apologies, that probably sounds as clear as mud!
*EDIT - MORE DETAIL *
So here is my Select query:
SELECT [MembershipTermID]
,[MemberStatusProgKey]
,[StartDate]
,[EndDate]
,[AdditionalDiscount]
,[EntryDateTime]
,[UpdateDateTime]
,[MembershipID]
,[AgentID]
,[PlanVersionID]
,[ForceThroughReference]
,[IsForceThrough]
,[NextTermPrePaid]
,[IsBillingMonthly]
,[CICSMEMBERNUM]
,[CICSHISTORY]
,[TMPSeqNoColumn]
,[LastPaymentDate]
,[PaidToDate]
,[IsIndeterminate]
,DATEDIFF(MONTH, PaidToDate, GETDATE()) as MonthsDifference
,dbo.FullMonthsSeparation (PaidToDate, GETDATE())
FROM [Apollo].[dbo].[MembershipTerm]
WHERE MemberStatusProgKey='DORMANT'
AND IsBillingMonthly=1
AND dbo.FullMonthsSeparation (PaidToDate, GETDATE()) >= 2
So using the rows that this returns I want to exec several stored procedures to update everything I need to in the database which would be affected by changing these rows. An example of one stored procedure is below, I think I will need to execute about 10 of these if not more:
USE [Apollo]
GO
/****** Object: StoredProcedure [dbo].[spCancellationDetailInsert] Script Date: 01/10/2012 10:21:50 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
/* ************************* INSERT *************************/
/* Auto Generated 11/29/2006 7:28:53 PM by Object Builder */
/* ************************* INSERT *************************/
ALTER Procedure [dbo].[spCancellationDetailInsert]
#StampUser char (10),
#CancellationDetailID int,
#RefundAmount float,
#OldEndDate datetime,
#EffectiveDate datetime,
#CancelDate datetime,
#ReasonCodeProgKey nvarchar (50)
As
/* insert CancellationDetail record */
Insert [CancellationDetail]
(
RefundAmount,
OldEndDate,
EffectiveDate,
CancelDate,
ReasonCodeProgKey
)
Values
(
#RefundAmount,
#OldEndDate,
#EffectiveDate,
#CancelDate,
#ReasonCodeProgKey
)
If ##Error <> 0 GoTo InsertErrorHandler
/* save the key of the new row created by the insert */
Select #CancellationDetailID = Scope_Identity()
/* add audit record */
Insert CancellationDetailAudit
(StampUser,
StampDateTime,
StampAction,
CancellationDetailID,
RefundAmount,
OldEndDate,
EffectiveDate,
CancelDate,
ReasonCodeProgKey)
Values
(#StampUser ,
GetDate() ,
'I',
#CancellationDetailID,
#RefundAmount,
#OldEndDate,
#EffectiveDate,
#CancelDate,
#ReasonCodeProgKey)
If ##Error <> 0 GoTo AuditInsertErrorHandler
Select
CancellationDetailID = #CancellationDetailID
Return (0)
InsertErrorHandler:
Raiserror ('SQL Error whilst inserting CancellationDetailrecord: Error Code %d',17,1,##Error)
With Log
Return (99)
AuditInsertErrorHandler:
Raiserror ('SQL Error whilst inserting audit record for CancellationDetailInsert: Error Code %d',17,1,##Error)
With Log
Return (99)
If you're asking what I think you are -
Stored procedures can contain (pretty much) any valid SQL statement. This includes returning multiple results sets, performing multiple updates and calling other stored procedures.
For example:
CREATE PROCEDURE usp_Sample AS
SELECT * FROM INFORMATION_SCHEMA.COLUMNS
SELECT * FROM INFORMATION_SCHEMA.TABLES
UPDATE Users SET Active = 0 WHERE ExpiredDate < GetDate()
SELECT Active, COUNT(*) FROM Users GROUP BY Active
EXEC usp_Sample2
GO
Obviously that's a rather artificial example, but assuming all the objects existed it'd run perfectly well.
In order to perform more queries at the same time you just need to append them after your select.
So you can do
Select *
From table1
Select *
From table2
Select *
From table3
as many times as you want and they'll all execute independently.
If you want to UPDATE based on a SELECT you usually do something like:
UPDATE table1
WHERE ID IN (SELECT ID FROM TABLE2)
with regards to your stored procedures it would help if you posted more details.

Cannot add an ORDER BY command to a stored procedure

I'm converting a stored procedure in some software I'm maintaining from SQL Server SQL to Informix SQL, and problems are abundant.
Basically I'm converting each section line-by-line until I have the whole thing converted.
I have the following CREATE PROCEDURE:
CREATE PROCEDURE ifxdbase:dc_buildSP (WorkID INT, CompNo smallint)
CREATE TEMP TABLE Items
(
Code smallint,
Qty int,
Total int
);
INSERT INTO Items
SELECT
tblDetails.code,
tblDetails.quantity,
tblHead.quantity
FROM
tblHead
INNER JOIN tblDetails ON (tblDetails.compno = tblDetails.compno AND tblDetails.id_num = tblHead.id_num)
WHERE tblHead.compno = CompNo AND tblHead.id_num = WorkID;
--ORDER BY tblDetails.code;
DROP TABLE Items;
END PROCEDURE
As it stands, this works fine, but when I uncomment the line --ORDER BY tblDetails.seqno; (and remove the semicolon from the previous line) I get a "-201 A syntax error has occurred" error.
Basically tblHead is a series of order headers and tblDetails is a table of the details of each of those orders. Selecting and joining the data works fine, trying to order it fails.
Ordering should work with anything from the original SELECT, IIRC, so I can't see what could be going wrong, here...
As stated here:
..... not all clauses and options of
the SELECT statement are available for
you to use in a query within an
INSERT statement. The following SELECT
clauses and options are not supported
by Informix in an INSERT statement:
FIRST and INTO TEMP
ORDER BY and UNION
so ORDER BY is not supported in the INSERT command in Informix.
I don't have something to test right now, but you could try something like this, as a workaround:
INSERT INTO Items
SELECT code, dQuantity, hQuantity
FROM (
SELECT
tblDetails.code,
tblDetails.quantity dQuantity,
tblHead.quantity hQuantity
FROM
tblHead
INNER JOIN tblDetails ON (tblDetails.compno = tblDetails.compno AND tblDetails.id_num = tblHead.id_num)
WHERE tblHead.compno = CompNo AND tblHead.id_num = WorkID;
ORDER BY tblDetails.code
);