Creating A Table Through Stored Procedure Shows An Syntax Error

May 26, 2000

hai guys,
i have written a stored procedure which creates a table ex:
USE PUBS
GO
IF EXISTS (SELECT * FROM SYSOBJECTS WHERE NAME = 'RC_STRPROC')
DROP PROCEDURE RC_STRPROC
GO
USE PUBS
GO
CREATE PROCEDURE RC_STRPROC
(@TBLNAME VARCHAR(35), @COLVAL1 VARCHAR(35), @COLVAL2 VARCHAR(35))
AS
IF EXISTS (SELECT * FROM SYSOBJECTS WHERE NAME = '@TBLNAME')
DROP TABLE @TBLNAME
CREATE TABLE @TBLNAME
(@COLVAL1, @COLVAL2)
GO
it gives an syntax error at '@tblname'
can u guys tell me the problem

thanks
hiss

View 2 Replies


ADVERTISEMENT

T-SQL Error In Creating A Stored Procedure That Has Three Parameters: Incorrect Syntax Near 'WHERE'

Feb 17, 2008

Hi all,

I copied the the following code from a book to the query editor of my SQL Server Management Studio Express (SSMSE):
///--MuCh14spInvTotal3.sql--///
USE AP --AP Database is installed in the SSMSE--
GO
CREATE PROC spInvTotal3
@InvTotal money OUTPUT,
@DateVar smalldatetime = NULL,
@VendorVar varchar(40) = '%'
AS

IF @DateVar IS NULL
SELECT @DateVar = MIN(InvoiceDate)

SELECT @InvTotal = SUM(InvoiceTotal)
FROM Invoices JOIN Vendors
WHERE (InvoiceDate >= @DateVar) AND
(VendorName LIKE @VendorVar)
GO
///////////////////////////////////////////////////////////////
Then I executed it and I got the following error:
Msg 156, Level 15, State 1, Procedure spInvTotal3, Line 12
Incorrect syntax near the keyword 'WHERE'.
I do not know what wrong with it and how to correct this problem.

Please help and advise.

Thanks,
Scott Chang

View 18 Replies View Related

Error Creating Table - Incorrect Syntax

May 27, 2014

Have been given this code to create a table

CREATE TABLE 'emaillist' (
'id' INT(11) NOT NULL AUTO_INCREMENT,
'clientname' VARCHAR(200) NOT NULL DEFAULT '0',
'email' VARCHAR(200) NOT NULL DEFAULT '0',
PRIMARY KEY ('id')
);

when I execute it says

Msg 102, Level 15, State 1, Line 1
Incorrect syntax near 'emaillist'.

What the correct code should be?

View 3 Replies View Related

SQL Server 2012 :: Syntax Error While Creating Table Dynamically

Apr 19, 2015

I am getting error when I am trying to create table on runtime

Declare @FileName varchar(100)
Declare @File varchar(100)
set @FileName='brkrte_121227102828'
SET @File = SUBSTRING(@FileName,1,CHARINDEX('_',@FileName)-1)
--=select @File

[Code] ....

Error massage:-
Msg 203, Level 16, State 2, Line 16

The name 'CREATE TABLE DataStaging.dbo.Staging_brkrte ( [COL001] VARCHAR (4000) NOT NULL, [Id] Int Identity(1,1), [LoadDate] datetime default getdate() )' is not a valid identifier.

How to resolve above error....

View 4 Replies View Related

ERROR:Syntax Error Converting Datetime From Character String. With Stored Procedure

Jul 12, 2007

Hi All,





i have migrated a DTS package wherein it consists of SQL task.

this has been migrated succesfully. but when i execute the package, i am getting the error with Excute SQL task which consists of Store Procedure excution.



But the SP can executed in the client server. can any body help in this regard.





Thanks in advance,

Anand

View 4 Replies View Related

Alias + Stored Procedure Syntax Error

Jun 21, 2008

Hi,

Im new to this forum and new also to SQL SERVER Edition Express.

Im trying to creat stored procedure. My main problem is that I need to display an alias consisting of 2 fields in a combobox (VB.Net) using also an innerjoin. Can anyone help me find my mistake please


My code is here and the error is :
-----------------------------------------------------------
Msg 156, Level 15, State 1, Procedure LA_suppName, Line 16
Incorrect syntax near the keyword 'INNER'.

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

@supplierFID int,
@supplierID int,
@LANo nvarchar(15) OUTPUT,
@suppName nvarchar(MAX) OUTPUT

AS

BEGIN
SET NOCOUNT ON;

-- Insert statements for procedure here

SELECT tb_LA.LANo, tb_supplier.suppName AS OrderSupplier
INNER JOIN tb_supplier ON tb_LA.supplierFID=tb_supplier.supplierID
Order by tb_LA.LANo

END

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

Eventually I would need to use tb_LA.LANo and make a query to populate the tb_LABooks in another combobox on selectvaluechanged. Is this possible please???


Many thanks

View 5 Replies View Related

Syntax Error When Building Up A Where Clause In Stored Procedure

Aug 9, 2006

Can anyone tell me why the line highlighted in blue produces the following error when I try to run this stored proc? I know the parameters are set properly as I can see them when debugging the SP.
I'm using this type of approach as my application is using the objectdatasource with paging. I have a similar SP that doesn't have the CategoryId and PersonTypeId parameters and that works fine so it is the addition of these new params that has messed up the building of the WHERE clause
The Error is: "Syntax error converting the varchar value '  WHERE CategoryId = ' to a column of data type int."
Thanks
Neil
CREATE PROCEDURE dbo.GetPersonsByCategoryAndTypeByName (@CategoryId int, @PersonTypeId int, @FirstName varchar(50)=NULL, @FamilyName varchar(50)=NULL, @StartRow int, @PageSize int)
AS
Declare @WhereClause varchar(2000)Declare @OrderByClause varchar(255)Declare @SelectClause varchar(2000)
CREATE TABLE #tblPersons ( ID int IDENTITY PRIMARY KEY , PersonId int , TitleId int NULL , FirstName varchar (50)  NULL , FamilyName varchar (50)  NOT NULL , FullName varchar (120)  NOT NULL , AltFamilyName varchar (50)  NULL , Sex varchar (6)  NULL , DateOfBirth datetime NULL , Age int NULL , DateOfDeath datetime NULL , CauseOfDeathId int NULL , Height int NULL , Weight int NULL , ABO varchar (3)  NULL , RhD varchar (8)  NULL , Comments varchar (2000)  NULL , LocalIdNo varchar (20)  NULL , NHSNo varchar (10) NULL , CHINo varchar (10)  NULL , HospitalId int NULL , HospitalNo varchar (20)  NULL , AltHospitalId int NULL , AltHospitalNo varchar (20)  NULL , EthnicGroupId int NULL , CitizenshipId int NULL , NHSEntitlement bit NULL , HomePhoneNo varchar (12)  NULL , WorkPhoneNo varchar (12)  NULL , MobilePhoneNo varchar (12)  NULL , CreatedBy varchar(40) NULL , DateCreated smalldatetime NULL , UpdatedBy varchar(40) NULL , DateLastUpdated smalldatetime NULL, UpdateId int )
SELECT @OrderByClause = ' ORDER BY FamilyName, FirstName'
SELECT @WhereClause = '  WHERE CategoryId = ' +  @CategoryId + ' AND PersonTypeId = ' + @PersonTypeIdIf NOT @Firstname IS NULLBEGIN SELECT @WhereClause = @WhereClause + ' AND FirstName LIKE ISNULL(''%'+ @FirstName + '%'','''')'ENDIf NOT @FamilyName IS NULLBEGIN SELECT @WhereClause = @WhereClause + ' AND (FamilyName LIKE ISNULL(''%'+ @FamilyName + '%'','''') OR AltFamilyName LIKE ISNULL(''%'+ @FamilyName + '%'',''''))'END
Select @SelectClause = 'INSERT INTO #tblPersons( PersonId, TitleId, FirstName, FamilyName , FullName, AltFamilyName, Sex, DateOfBirth, Age, DateOfDeath, CauseOfDeathId, Height, Weight, ABO, RhD, Comments, LocalIdNo, NHSNo, CHINo, HospitalId, HospitalNo, AltHospitalId, AltHospitalNo, EthnicGroupId, CitizenshipId, NHSEntitlement, HomePhoneNo, WorkPhoneNo, MobilePhoneNo, CreatedBy, DateCreated, UpdatedBy, DateLastUpdated, UpdateId)
SELECT  PersonId, TitleId, FirstName, FamilyName , FullName, AltFamilyName, Sex, DateOfBirth, Age, DateOfDeath, CauseOfDeathId, Height, Weight, ABO, RhD, Comments, LocalIdNo, NHSNo, CHINo, HospitalId, HospitalNo, AltHospitalId, AltHospitalNo, EthnicGroupId, CitizenshipId, NHSEntitlement, HomePhoneNo, WorkPhoneNo, MobilePhoneNo, CreatedBy, DateCreated, UpdatedBy, DateLastUpdated, UpdateId
 FROM vw_GetPersonsByCategoryAndType '
EXEC (@SelectClause + @WhereClause +@OrderByClause)

View 1 Replies View Related

Error While Creating A Stored Procedure

Aug 30, 2012

I am working with SQL Server 2005 Express and have written a query which works well in when run it in the managment console as a select query.

When I try to create a stored procedure out of it, I get the following error:

Code:
Msg 102, Level 15, State 1, Procedure sp_SegmentationList_ByorderID, Line 20 Incorrect syntax near ';'.

Procedure is below:

Code:
USE [ARC_Test]
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[sp_SegmentationList_ByorderID]
@OrderID int

[code].....

View 3 Replies View Related

Receiving Error 156 - Incorrect Syntax When Compiling Stored Procedure

May 14, 2008

The following query works fine in query analyzer, but when I add it to my stored procedure I receive an error 156. How do I work around this?

select distinct(dateposted)
from billingprocedures bp1,
billingprocedureordercomponentvalues bpocv,
ordercomponentvalues ocv
where bp1.billingid = @billingid
and bp1.procedureid = bpocv.billingprocedureid
and bpocv.ordercomponentvalueid = ocv.ordercomponentvalueid

Thanks,
Bryan

View 12 Replies View Related

Error Message While Creating Stored Procedure

Jan 10, 2008



I'm creating a simple stored procedure:


create procedure spzipcode
(
@TableName nvarchar(10)
)
as
select distinct customer_code
from @TableName
GO

When running the code above, I get the following error message:


Server: Msg 137, Level 15, State 2, Procedure spzipcode, Line 8
Must declare the variable '@TableName'.

I can't figure out what I'm doing wrong.

Does anyone have an answer:

View 6 Replies View Related

Creating Stored Procedure That Inserts Value In Table

Feb 13, 2008

I am using vwde2008 and created db and table. i want to create a stored procedure that will insert values. I am bit lost on how write this.
this is my table info
table = BusinessInfo
Columns = BusinessID, BusinessName, BusinessAddress
how can i create a stored procedure ?

View 1 Replies View Related

Creating A Table Inside A Stored Procedure

Feb 26, 2004

I am trying to creating a table inside a stored procedure using SQL that works fine in Query Analyzer. However, when I check the syntax I get the following message:

Error 208: Invalid object name '##OPTIONSEX'

I am using the following SQL script:

CREATE PROCEDURE [dbo].[Test2] AS

CREATE TABLE ##OPTIONSEX
(
OPTION_PLAN VARCHAR(50),
TOT_OPTIONS_EXCHANGED FLOAT NULL
)

GO

INSERT ##OPTIONSEX

SELECT
B.COMPONENT,
TOT_OPTIONS_EXCHANGED = SUM(A.UNITS)
FROM TBLEXERCISEOPTIONS A, TBLCOMPONENT B
WHERE B.COMPONENTID = A.COMPONENTID
GROUP BY B.COMPONENT

GO

Any help getting this to run correctly would be appreciated.

View 3 Replies View Related

It Gives Code Page Error On Creating Stored Procedure !!!!!

Jun 28, 2006

Hi
I was transferring objects of my existing database from remote to local and I recieved this error during the DTS process. It was on the transfer of the following stored procedure. I tried to create this SP manually but its giving me the same error and doesn't create it. I don't know how to fix it.
I wonder if somebody can help me! Thanks in Advance
[450] Code page translations are not supported for the text data type. From: 1252 To: 1256.
CREATE  PROCEDURE dbo.Novasoft_DL_UpdateDownloadsRating @RatingID int,  @DownloadID int,  @UserID int,  @Rating int, @Comment text, @ReviewDate datetime, @CommentName nvarchar(50) ASUPDATE dbo.Novasoft_DL_DownloadsRating SET [DownloadID] = @DownloadID, [UserID] = @UserID, [Rating] = @Rating, [Comment] = @Comment, [ReviewDate] = @ReviewDate, [CommentName] = @CommentNameWHERE [RatingID] = @RatingID
GO

View 1 Replies View Related

Creating New Table From Passed Variabe In MSSQL Stored Procedure

Mar 2, 2004

Hi there i really cant understand why this should be a problem... it seems that i cant create a table from a stored procedure when passing the tablenam from application like this...

CREATE PROCEDURE dbo.CreateTable
@TableName NVARCHAR(50)
AS
BEGIN

create table @TableName ([id] int identity(1,1),[diller] int)

end
GO

THIS CANT BE TRUE !!!!!!!!

View 4 Replies View Related

Creating Stored Procedure With Temp Table - Pass 6 Parameters

Sep 9, 2014

I need to create a Stored Procedure in SQL server which passes 6 input parameters Eg:

ALTER procedure [dbo].[sp_extract_Missing_Price]
@DisplayStart datetime,
@yearStart datetime,
@quarterStart datetime,
@monthStart datetime,
@index int
as

Once I declare the attributes I need to create a Temp table and update the data in it. Creating temp table

Once I have created the Temp table following query I need to run

SELECT date FROM #tempTable
WHERE #temp.date NOT IN (SELECT date FROM mytable WHERE mytable.date IN (list-of-input-attributes) and index = @index)

The above query might return null result or a date .

In case null return output as "DataNotMissing"
In case not null return date and string as "Datamissing"

View 3 Replies View Related

Creating Stored Procedure To Use With Crystal Reports - Table Join

Dec 30, 2014

I am a newbie to SQL and I am trying to create a stored procedure to use with Crystal Reports.

I don't understand why I am having trouble joining tables to the Member table. These table joins have worked in the past.

Create Proc rpmb_FamilyPortraitDirectoryP1Test
(
@ChurchId int,
@StartFamilyName varchar(50),
@EndFamilyName varchar(50),
@MemberTypeId varchar(max) = Null,

[Code] ....

View 4 Replies View Related

Creating A Dynamic Global Temp Table Within A Stored Procedure

Sep 7, 2006

hi,I wish to create a temporary table who's name is dynamic based on theargument.ALTER PROCEDURE [dbo].[generateTicketTable]@PID1 VARCHAR(50),@PID2 VARCHAR(50),@TICKET VARCHAR(20)ASBEGINSET NOCOUNT ON;DECLARE @DATA XMLSET @DATA = (SELECT dbo.getHistoryLocationXMLF (@PID1, @PID2) as data)CREATE TABLE ##@TICKET (DATA XML)INSERT INTO ##@TICKET VALUES(@DATA)ENDis what i have so far - although it just creates a table with a name of##@TICKET - which isn't what i want. I want it to evaluate the name.any ideas?

View 16 Replies View Related

Stored Procedure Passes Test In Gridview, But Nothing Shows Up On The Page

Feb 25, 2008

Like the subject says I have tested the SP in Gridview. Everything looks fine. But when run nothing shows up on the page.
I have tried using QueryStrings to pass the data and Controls.
Here is the Gridview Code:<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
BackColor="White" BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px"
CellPadding="4" DataSourceID="SqlDataSource1">
<FooterStyle BackColor="#99CCCC" ForeColor="#003399" />
<RowStyle BackColor="White" ForeColor="#003399" />
<Columns><asp:BoundField DataField="FirstName" HeaderText="FirstName"
SortExpression="FirstName" /><asp:BoundField DataField="LastName" HeaderText="LastName"
SortExpression="LastName" /><asp:BoundField DataField="EthnicID" HeaderText="EthnicID"
SortExpression="EthnicID" /><asp:BoundField DataField="Gender" HeaderText="Gender"
SortExpression="Gender" /><asp:BoundField DataField="Height" HeaderText="Height"
SortExpression="Height" /><asp:BoundField DataField="Weight" HeaderText="Weight"
SortExpression="Weight" />
<asp:BoundField DataField="Hair" HeaderText="Hair" SortExpression="Hair" />
<asp:BoundField DataField="Eyes" HeaderText="Eyes" SortExpression="Eyes" />
<asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
<asp:BoundField DataField="State" HeaderText="State" SortExpression="State" />
</Columns>
<PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" />
<SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
<HeaderStyle BackColor="#003399" Font-Bold="True" ForeColor="#CCCCFF" />
</asp:GridView>
 
 
Here is the Datasource:<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:SQL2005_311004_modelsystemConnectionString %>"
SelectCommand="spSearch" SelectCommandType="StoredProcedure">
<SelectParameters><asp:QueryStringParameter DefaultValue="" Name="FirstName"
QueryStringField="fn" Type="String" />
<asp:QueryStringParameter Name="LastName" QueryStringField="ln" Type="String" />
<asp:Parameter Name="EthnicID" Type="String" />
<asp:Parameter Name="Gender" Type="String" />
<asp:Parameter Name="Height" Type="String" />
<asp:Parameter Name="weight" Type="String" />
<asp:Parameter Name="Hair" Type="String" />
<asp:Parameter Name="Eyes" Type="String" />
<asp:Parameter Name="City" Type="String" />
<asp:Parameter Name="State" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
 
I hope you can help me with this one!!!

View 2 Replies View Related

Creating A Stored Procedure That Will Summarize Data In A Table Into A Table Reflecting Period Data Using An Array Type Field

Sep 20, 2007

I am attempting to create a stored procedure that will launch at report runtime to summarize data in a table into a table that will reflect period data using an array type field. I know how to execute one line but I am not sure how to run the script so that it not only summarizes the data below but also creates and drops the table.

Any help would be greatly appreciated.

Current Table

Project | Task | Category | Fiscal Year | Fiscal Month | Total Hours
---------------------------------------------------------------------------------------------------------
Proj 1 | Task 1 | Cat 1 | 2007 | 01 | 40
Proj 1 | Task 1 | Cat 2 | 2007 | 02 | 20
Proj 1 | Task 1 | Cat 3 | 2007 | 03 | 35
Proj 1 | Task 1 | Cat 1 | 2008 | 01 | 40
Proj 1 | Task 1 | Cat 2 | 2008 | 02 | 40
Proj 1 | Task 1 | Cat 3 | 2008 | 03 | 40

Proposed Table

Project | Task | Category | Fiscal Month 01 | Fiscal Month 02 | Fiscal Month 03 | Fiscal Year
---------------------------------------------------------------------------------------------------------------------------------------------------
Proj 1 | Task 1 | Cat 1 | 40 | 0 | 0 | 2007
Proj 1 | Task 1 | Cat 2 | 0 | 20 | 0 | 2007Proj 1 | Task 1 | Cat 3 | 0 | 0 | 35 | 2007
Proj 1 | Task 1 | Cat 1 | 40 | 0 | 0 | 2008

Proj 1 | Task 1 | Cat 2 | 0 | 40 | 0 | 2008
Proj 1 | Task 1 | Cat 3 | 0 | 0 | 40 | 2008

Thanks,
Mike Misera

View 6 Replies View Related

SQLS7&&VB6 Date Update Gives Syntax (Not Date Format) Error In Stored Procedure

Jul 20, 2005

Hi,I have a problem with updating a datetime column,When I try to change the Column from VB I get "Incorrect syntax near'942'" returned from [Microsoft][ODBC SQL Server Driver][SQL Server]'942' is the unique key column valueHowever if I update any other column the syntax is fineThe same blanket update query makes the changes no matter what isupdatedThe problem only happens when I set a unique key on the date field inquestionKey is a composite of an ID, and 2 date fieldsIf I allow duplicates in the index it all works perfectlyI am trying to trap 'Duplicate value in index' (which is working onother non-date columns in other tables)This is driving me nutsAny help would be appreciated

View 5 Replies View Related

Syntax For Creating Duplicate Table

Nov 29, 2000

Hi
Is there a syntax similar to the oracle in SQL Server?
Oracle statement: create table table2 as select * from table1

which will create table2 with exactly the same structure
and records as table 1

thanks
Liju

View 2 Replies View Related

Error Inserting Image Into SQL Server2000 Table From Pocket PC Application Only When Using Stored Procedure In Table Adapter Wiz

Apr 24, 2008

My Pocket PC application exports signature as an image. Everything is fine when choose Use SQL statements in TableAdapter Configuration Wizard.


main.ds.MailsSignature.Clear();

main.ds.MailsSignature.AcceptChanges();


string[] signFiles = Directory.GetFiles(Settings.signDirectory);


foreach (string signFile in signFiles)

{


mailsSignatureRow = main.ds.MailsSignature.NewMailsSignatureRow();

mailsSignatureRow.Singnature = GetImageBytes(signFile); //return byte[] array of the image.

main.ds.MailsSignature.Rows.Add(mailsSignatureRow);

}


mailsSignatureTableAdapter.Update(main.ds.MailsSignature);

But now I am getting error "General Network Error. Check your network documentation" after specifying Use existing stored procedure in TableAdpater Configuration Wizard.


ALTER PROCEDURE dbo.Insert_MailSignature( @Singnature image )

AS

SET NOCOUNT OFF;

INSERT INTO MailsSignature (Singnature) VALUES (@Singnature);



SELECT Id, Singnature FROM MailsSignature WHERE (Id = SCOPE_IDENTITY())

For testing I created a desktop application and found that the same Code, same(Use existing stored procedure in TableAdpater Configuration Wizard) and same stored procedure is working fine in inserting image into the table.

Is there any limitation in CF?

Regards,
Professor Corrie.

View 3 Replies View Related

Error In Filling A Table With A Stored Procedure

Jan 4, 2007

When I run the code below, I get
a table with "In order to evaluate an indexed property, the property
must be qualified and the arguments must be explicitly supplied by the
user." as the contents... 
Public Function ReturnTable(ByVal strName As String, ByVal alParameters As ArrayList, ByVal strTable As String) As DataSet
        Dim sqlSP As New SqlCommand
        sqlSP.CommandTimeout = 120
        sqlSP.Connection = sqlConn
        sqlSP.CommandType = CommandType.StoredProcedure
        sqlSP.CommandText = strName

        AddParameters(sqlSP.Parameters, alParameters)

        Dim dsDataSet As New DataSet()

        sqlConn.Open()

        Dim sqlDataAdapter As New SqlDataAdapter(sqlSP)
        sqlDataAdapter.Fill(dsDataSet, strTable)
        sqlConn.Close()

        Return dsDataSet

    End Function

 AddParameters is a function which adds each of the parameters in the
array list to the sqlSP parameter collection... In SQL Profiler, the sp
is called and runs and returns results... But a dataset with one table
and the above msg is returned... 

View 2 Replies View Related

Passing Table Name In Stored Procedure Got Error

May 13, 2008

ALTER PROCEDURE [dbo].[sp_STATEWLEVEL_DAILY]
@STATE varchar(50),@TBLNAME varchar(50)

AS
BEGIN TRANSACTION -- Start the transaction
TRUNCATE TABLE @TBLNAME;
SELECT
t1.Date_Taken as 'DATE', t1.Time as 'TIME',
t1.Main_ID as 'MAIN_ID', t1.WATER_ULEVEL as 'WATER_ULEVEL'
FROM dbo.SEL t1 INNER JOIN dbo.station_info t2
ON t1.Main_ID=t2.Main_ID
WHERE t2.STATE=@STATE
AND t1.Date_Taken=CONVERT(VARCHAR(10), GETDATE(), 101)
ORDER BY t1.Date_Taken, t1.Time

-- See if there is an error
IF @@ERROR <> 0
-- There's an error b/c @ERROR is not 0, rollback
ROLLBACK
ELSE
COMMIT -- Success! Commit the transaction

Error said Incorrect syntax near '@TBLNAME'.

View 8 Replies View Related

Error In Stored Procedure While Working With Temp. Table

May 31, 2007

Creating a temporary table in stored procedure and using a sql query to insert the data in temp. table.I am facing the error as :
String or binary data would be truncated.The statement has been terminated.
The procedure i created is as :
ALTER PROCEDURE fetchpersondetails
AS
CREATE Table #tempperson (personID int,FirstName nvarchar(200),LastName nvarchar(250),title nvarchar(150),Profession nvarchar(200),StreetAddress nvarchar(300),
StateAddress nvarchar(200),CityAddress nvarchar(200),CountryAddress nvarchar(200),ZipAddress nvarchar(200),Telephone nvarchar(200),Mobile nvarchar(200),
Fax nvarchar(200),Email nvarchar(250),NotesPub ntext,Affiliation nvarchar(200),Category nvarchar(200))
 
Insert into #tempperson
SELECT dbo.tblperson.personID, ISNULL(dbo.tblperson.fName, N'') + ' ' + ISNULL(dbo.tblperson.mName, N'') AS FirstName, dbo.tblperson.lname AS LastName,
dbo.tblperson.honor AS Title, dbo.tblperson.title AS Profession, dbo.tblperson.street + ' ' + ISNULL(dbo.tblperson.suite, N'') AS StreetAddress,
dbo.tblperson.city AS cityaddress, dbo.tblperson.state AS stateaddress, dbo.tblperson.postalCode AS zipaddress,
dbo.tblperson.Phone1 + ',' + ISNULL(dbo.tblperson.Phone2, N'') + ',' + ISNULL(dbo.tblperson.Phone3, N'') AS Telephone,
dbo.tblperson.mobilePhone AS mobile, dbo.tblperson.officeFax + ',' + ISNULL(dbo.tblperson.altOfficeFax, N'') + ',' + ISNULL(dbo.tblperson.altOfficeFax2,
N'') AS Fax, ISNULL(dbo.tblperson.Email1, N'') + ',' + ISNULL(dbo.tblperson.Email2, N'') + ',' + ISNULL(dbo.tblperson.Email3, N'') AS Email,
dbo.tblperson.notes AS NotesPub, dbo.tblOrganizations.orgName AS Affiliation, dbo.tblOrganizations.orgCategory AS Category,
dbo.tblCountry.countryNameFull AS countryaddress
FROM dbo.tblperson INNER JOIN
dbo.tblOrganizations ON dbo.tblperson.orgID = dbo.tblOrganizations.orgID INNER JOIN
dbo.tblCountry ON dbo.tblperson.countryCode = dbo.tblCountry.ISOCode
 
please let me know the solurion of this error. 
 

View 2 Replies View Related

#Table Not Found Error Using Stored Procedure For DataSet

Aug 29, 2007

Hi all

I have a procedure where I am inserting some elements into #Table and then finally get the datset I need.
Now when I am using this procedure as dataset to my report, it throws up the following error:





Invalid object Name "#TEMP2".

The data that I retrieve is similar to the data that I get from this query in the post by Manivannan.D.Sekaran
http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1871478&SiteID=1

Is it because my columns are generated on the fly that I am not able to retrieve the column headers appropriately. If so can someone suggest a way over to this?

I am not sure should I posting it here or in T-SQL Forum.








View 17 Replies View Related

Stored Procedure Syntax

Jun 27, 2006

This is probably a very simple question but i would appreciate some help
I have the following stored procedure and I am getting the error message
"The objects "aspnet_Users" And "aspnet_Users" in the FROM clause have the same exposed names. Use correlation names to distinguish them"
Can anyone tell me where I am going wrong.
many thanks
Martin
ALTER PROCEDURE [dbo].[SP_CreateOrder](@CartID char (36),@UserId Varchar (50),@OrderTotal decimal (8))
AS
Declare @OrderID int
INSERT INTO  Orders (UserID,Name,Address1,Address2,City,State,Country,Zip,OrderTotal)
SELECT aspnet_Users.UserId,aspnet_Users.Name,aspnet_Profile.Address1,aspnet_Profile.Address2,aspnet_Profile.City,aspnet_Profile.State,aspnet_Profile.Country,aspnet_Profile.Zip,@OrderTotal
FROM aspnet_Users,aspnet_Profile Join aspnet_Users On aspnet_Profile.UserId=aspnet_Users.UserId
WHERE asp_Users.UserId=@UserId
SET @OrderID = @@IDENTITY
INSERT INTO OrderDetails (UserId,OrderID,ProductID,Name,Cost,Quantity)
SELECT  @UserID,@OrderID,Products.ProductID,Products.Name,Products.Cost,ShoppingCart.Quantity
From aspnet_User,Products Join ShoppingCart ON Products.ProductID =ShoppingCart.ProductIDWHERE  aspnet_User.Userid=@UserId AND ShoppingCart.CartID = @CartID
EXEC SP_DeleteShoppingCart @CartIDSELECT @OrderIDGO
 

View 2 Replies View Related

Does This Stored Procedure Syntax Look Okay?

Dec 7, 2006

Does this Stored Procedure Syntax look okay?I'm trying to call it using classic asp with the following code but get an error on calling the stored procedure:set objComm    = Server.CreateObject("ADODB.Command")

objComm.ActiveConnection = sstrDsnString 'You can also just specify a connection string here
objComm.CommandText = "editorTAmonthlyReport" ' stored procedure name
objComm.CommandType = adCmdStoredProc 'Requires the adovbs.inc file or typelib meta tag
'Add Input Parameters to date and from date variables - dtFrom and dtTo
objComm.Parameters.Append.CreateParameter("@dtFrom", adDate, adParamInput, 9)
objComm.Parameters.Append.CreateParameter("@dtTo", adDate, adParamInput, 9)
 CREATE PROCEDURE editorTAmonthlyReport
@FromDate DateTime,
@ToDate DateTime
As

Select
U.UserID,
U.Title,
U.FirstName,
U.Surname,
TAU.UserPosition,
U.Email,
A.AgencyName,
A.AddressLine1,
A.AddressLine2,
A.Town,
A.County,
A.Postcode,
C.Country,
Coalesce(U.Phone,A.Phone) As Phone,
TAU.DateOfCreation
From
[user] U LEFT OUTER JOIN MyTrafalgarUser MTU
   ON MTU.userID=U.UserID
INNER JOIN TravelAgencyUser TAU
   ON U.UserID=TAU.UserID
INNER JOIN Agency A
   ON TAU.AgencyID=A.AgencyID
INNER JOIN Country C
   ON A.CountryID=C.CountryID
Where ( u.userid > 34657 AND DateDiff(d,TAU.DateOfCreation, @FromDate) < 0 )
and datediff(d,TAU.DateOfCreation, @ToDate) > 0
ORDER BY TAU.DateOfCreation
GO

View 2 Replies View Related

STORED PROCEDURE Syntax

Jun 8, 2007

Hi All
I will like to allow guess users to add items to the shopping cart (using a temp shoppingcartID):
' If user is not authenticated, either fetch (or issue) a new temporary cartID
If Not context.Request.Cookies("MMDotNetID") Is Nothing ThenReturn context.Request.Cookies("MMDotNetID").Value.ToString
Else
' Generate a new random GUID using System.Guid ClassDim tempCartId As Guid = Guid.NewGuid()
' Send tempCartId back to client as a cookie
context.Response.Cookies("MMDotNetID").Value = tempCartId.ToString()
context.Response.Cookies("MMDotNetID").Expires = DateTime.Now.AddMonths(1)
' Return tempCartId
Return tempCartId.ToString
' If user is authenticated I use the userID to store the items in the Shopping Cart
'If the user logon after adding some items to the cart I need to Migrate the old items.
'But my STORED PROCEDURE is not working properly:ALTER PROCEDURE MM_SP_ShoppingCartMigrate (
@OriginalCartId nvarchar(50),
@NewCartId nvarchar(50))
As
IF EXISTS(SELECT * FROM MM_SP_ShoppingCart
WHERE CartID = @NewCartId)
BEGIN
 
DECLARE @CountItemsInOldCard intSELECT @CountItemsInOldCard = MM_SP_ShoppingCart.Quantity
FROM MM_SP_ShoppingCartWHERE CartID = @OriginalCartId
 
DECLARE @CountItems intSELECT @CountItems = MM_SP_ShoppingCart.Quantity
FROM MM_SP_ShoppingCartWHERE CartID = @NewCartId
 UPDATE MM_SP_ShoppingCart
SET Quantity = @CountItems + @CountItemsInOldCardWHERE CartID = @NewCartId
END
ELSE
UPDATE
MM_SP_ShoppingCart
SET
CartID = @NewCartId
WHERE
CartID = @OriginalCartId
DELETE FROM MM_SP_ShoppingCart
WHERE CartID = @OriginalCartId
RETURN
'Any help
 
 

View 2 Replies View Related

Need Help With A Stored Procedure Syntax

Jul 20, 2005

I need help in writing a stored procedure on SQL Server 2000.Basically the stored procedure's primary task is to generate invoicerecords and insert the records in a invoice table. In order togenerate the invoice records, I have an initial table which arebasically Day Records. The task that I would like to complete is toselect all records from that initial table and I guess put them into atemp table. Now that i have my temp table, I would like to loop thruthe table record by record, and do inserts in the invoice table. Icant seem to figure out the syntax since I am somewhat weak in TSQLProgramming. I would appreciate any assistance on this forum or to myemail. Also If you need some pseudocode for the process or the DDL forthe initial table and the invoice table, I can definitely post that inthe forum possibly in the next thread. Please advise, I would need afull written syntax to get me started since i have some otherprocesses that I would need to build using the template. Thanks again.

View 7 Replies View Related

Stored Procedure Syntax Help

Jul 20, 2005

I'm enhancing a large ASP application by replacing raw SQL statementsin the code with calls to stored procedures. I've seen thisrecommended in many places to increase SQL Server effieicency.Replacing select statements is going fine but I hit a sticking pointwhen trying to replace an update statement.Currently, I use this kind of statement a lot in my ASP:sql = "update"sql = sql & " field1 = value1"sql = sql & ",field2 = value2"If Len(value3) Then sql = sql & ",field3 = value3"sql = sql & " where ...., etc, etcThe important part here is checking if "value3" has a value beforeinserting it into my SQL statement. So how can I put this updatestatement into a stored procedure, pass in values for value1, value2,and value3, and leave off the value3 part of the update if value3comes in as null.Thanks all.

View 3 Replies View Related

Stored Procedure Syntax

Jul 20, 2005

Hi AllIm trying to use the code at the bottom of this message inside my storedprocedure and when i execute the procedure in query analyzer i get thefollowing error:Server: Msg 207, Level 16, State 3, Line 1Invalid column name 'H'.This error happens a few times and im pretty sure it is because the selectstatement needs the ' around the data that is being searched. This is whatthe select statement looks like for me:SELECT * FROM Locations WHERE GroupID = H OR GroupID = HM OR GroupID = HMSOR GroupID = HMSS OR GroupID = HMSSR OR GroupID = HMSSRVAnd im pretty sure it is failing because sql wants the select statement tolook like this:SELECT * FROM Locations WHERE GroupID = 'H' OR GroupID = 'HM' OR GroupID ='HMS' OR GroupID = 'HMSS' OR GroupID = 'HMSSR' OR GroupID = 'HMSSRV'Am i thinking along the right lines with this ? If so does anybody know of away that i can put the ' mark around the the data that is being searched for? Any help is greatly appreciatedThanksCREATE PROCEDURE [dbo].[TestSP]@MachineName VarChar(50),@UserName VarChar(50)ASDECLARE @MachineLength Char(2) /* Local Machine Name Length */DECLARE @SrchInt Char(1) /* Search Loop Integer Counter */DECLARE @SqlStr VarChar(300) /* SQL Select String */DECLARE @CurrMach VarChar(50) /* Local Machine Name Counter */SET @SrchInt = 1SET @MachineLength = Len(@MachineName)SET @SqlStr = 'SELECT * FROM Locations WHERE GroupID = 'WHILE @SrchInt <= @MachineLengthBEGINSET @CurrMach = LEFT(@MachineName,@SrchInt)IF @SrchInt = 1BEGINSET @SqlStr = @SqlStr + LEFT(@MachineName,1)ENDIF @SrchInt > 1BEGINSET @SqlStr = @SqlStr + ' OR GroupID = ' + @CurrMachENDSET @SrchInt = @SrchInt + 1PRINT @SqlStrENDEXEC (@SqlStr)GO

View 4 Replies View Related

Stored Procedure Syntax Problem

Jul 27, 2006

This is probably a simple question but i would appreciate some help.
I have a stored procedure that i want want first to check if a customer
exists in the customer table and if a customer doesnt exist to insert values.
I know that there are other ways to do this but i was wondering if itwas possible to do this only within the stored procedure.
I have been using:
SELECT COUNT(*)FROM customersWHERE customerID=@customerID
IF COUNT(*)=0............
(Insert statement follows) 
But the new customer values are not being inserted.Can anyone tell me where I am going wrong or suggest a diferent wat of doing this?
Many Thanks
martin
BY the way the rows seem to be counted as the information is inserted if i use If COUNT(*)>0 but the insert is  not happening with the code above.
 

View 2 Replies View Related







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