What Is Wrong With This Procedure?
Jul 23, 2005
I get the following error for this procedure:
Server: Msg 156, Level 15, State 1, Procedure Trig_Ins_TrackingNumbers,
Line 6
Incorrect syntax near the keyword 'IF'.
CREATE TRIGGER Trig_Ins_TrackingNumbers ON TrackingNumbers
INSTEAD OF INSERT
AS
BEGIN
IF (SELECT ISNUMERIC(InvoiceNumber) FROM inserted)
IF(EXISTS (SELECT I.InvoiceNumber
FROM Invoices I, inserted Ins
WHERE I.InvoiceNumber=CAST(Ins.InvoiceNumber AS INT)))
INSERT INTO TrackingNumbers(InvoiceNum,InvoiceNumber,
TrackingNumber)
SELECT CAST(InvoiceNumber AS INT), InvoiceNumber, TrackingNumber
FROM inserted
END
View 4 Replies
ADVERTISEMENT
Apr 6, 2004
please take a look at this strored proxedure and tell what is wrong with it?
CREATE PROCEDURE sp_Pictures_CreateTextPost
@UserID Int,
@Country varchar (2),
@Description varchar (1000),
@PostID int output
AS
BEGIN TRANSACTION
INSERT INTO Pictures_TextPosts
(UserID, Country, Description)
VALUES
(@UserID, @Country, @Description)
IF @@ERROR <> 0
ROLLBACK TRANSACTION
ELSE
BEGIN
COMMIT TRANSACTION
UPDATE Accounts_Users SET Count_InsertText = Count_InsertText + 1 Where UserID = @UserID
SET @PostID = @@IDENTITY
RETURN 1
END
i run this sp on MS SQL server on my local machine and it works fine. now i move the same sp to the host server and it no longer works. it is the problem with this sp as i run sql query to test it. i use the ASP.NET Enterprise Manager to insert this sp. can someone please help?
one hint: on the host server, if i add 'GO' to the end of the sp, error occured.
View 6 Replies
View Related
Apr 8, 2004
I have written an ASP.net app that iterates through the controls on my page if the are checkboxlist or radiobuttonlist controls, the id and value are serialized into an xml file which is sent to a SQL 2000 stored procedure where the xml data is inserted into a couple of tables.
I captured the xml that is being sent:
<?xml version="1.0"?>
<Schema7Ihsurveyresponse xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" surveyid="1" Userid="14">
<ihsresponsedetail question="Q1" response="0" result="1" />
<ihsresponsedetail question="Q2" response="0" result="1" />
<ihsresponsedetail question="Q3" response="0" result="1" />
<ihsresponsedetail question="Q5" response="0" result="1" />
<ihsresponsedetail question="Q6" response="0" result="1" />
<ihsresponsedetail question="Q7" response="0" result="1" />
<ihsresponsedetail question="Q8" response="0" result="1" />
<ihsresponsedetail question="Q9" response="0" result="1" />
<ihsresponsedetail question="Q10" response="0" result="1" />
<ihsresponsedetail question="Q11" response="0" result="1" />
<ihsresponsedetail question="Q12" response="0" result="1" />
<ihsresponsedetail question="Q13" response="0" result="1" />
<ihsresponsedetail question="Q14" response="0" result="1" />
<ihsresponsedetail question="Q15" response="0" result="1" />
<ihsresponsedetail question="Q17" response="0" result="1" />
<ihsresponsedetail question="Q18" response="0" result="1" />
<ihsresponsedetail question="Q19" response="0" result="1" />
<ihsresponsedetail question="Q20" response="0" result="1" />
<ihsresponsedetail question="Q21" response="0" result="1" />
<ihsresponsedetail question="Q23" response="0" result="1" />
<ihsresponsedetail question="Q24" response="0" result="1" />
<ihsresponsedetail question="Q25" response="0" result="1" />
<ihsresponsedetail question="Q26" response="0" result="1" />
<ihsresponsedetail question="Q27" response="0" result="1" />
<ihsresponsedetail question="Q28" response="0" result="1" />
<ihsresponsedetail question="Q29" response="0" result="1" />
<ihsresponsedetail question="Q30" response="0" result="1" />
<ihsresponsedetail question="Q31" response="0" result="1" />
<ihsresponsedetail question="Q32" response="0" result="1" />
<ihsresponsedetail question="Q33" response="0" result="1" />
<ihsresponsedetail question="Q34" response="0" result="1" />
<ihsresponsedetail question="Q35" response="0" result="1" />
<ihsresponsedetail question="Q36" response="0" result="1" />
<ihsresponsedetail question="Q37" response="0" result="1" />
<ihsresponsedetail question="Q38" response="0" result="1" />
<ihsresponsedetail question="Q39" response="0" result="1" />
<ihsresponsedetail question="Q40" response="0" result="1" />
</Schema7Ihsurveyresponse>
and here is my stored procedure:
CREATE PROCEDURE Insertresponsedetails
@XML TEXT
AS
SET NOCOUNT ON
SET XACT_ABORT ON
-- Access is not restricted.
insert into tempxml ([xml]) values (@xml)
DECLARE @idoc INT, @responseid int
EXECUTE sp_xml_preparedocument @idoc OUTPUT, @XML, '<ns xmlns:a="http://interhealthusa.com/surveyresponse.xsd"/>'
if @@error<>0
begin
select(-1)
return
end
BEGIN TRANSACTION
insert into ihsurveyresponse (userid, Surveyid, Responsedate)
select userid, surveyid, getdate()
from openxml(@idoc, '/schema7ihsurveyresponse', 1)
with (userid int, surveyid int)
if @@error<>0
begin
rollback transaction
select 2
return
end
set @responseid = scope_identity()
INSERT INTO IHSResponsedetail (Question,Result, Response)
SELECT Question, Result, @responseid
FROM OPENXML (@idoc, '/schema7ihSurveyResponse/ihsresponsedetail')
WITH ( [Question] char(10) '@Question', Result int '@Result')
EXECUTE sp_xml_removedocument @idoc
if @@error<>0
begin
rollback transaction
select 3
return
end
COMMIT TRANSACTION
select @responseid
GO
If anyone has any insight I would really appreciate the assistance.
View 1 Replies
View Related
Sep 20, 2001
Hiya, all!
I've got this stored procedure:
CREATE Procedure CheckReOccurences
@PatID INT, @CPT CHAR(7),@DOS DATETIME,@DRecur SMALLINT
AS
DECLARE @DaysElapsed INT
SET @DaysElapsed = (SELECT DATEDIFF(day,ISNULL((SELECT MAX(ServiceDate) FROM VouchersDetail WHERE PatID = @PatID AND ProcCode = @CPT),01/01/1900),@DOS))
IF @DaysElapsed < @DRecur --Patient has had procedure done too recently
BEGIN
PRINT 'Too Recent-Only ' + str(@dayselapsed) + ' days elapsed'
RETURN 0
END
ELSE --More time has elapsed since procedure last performed than is necessary
BEGIN
PRINT 'Not Too Recent- ' + str(@dayselapsed) + ' days elapsed'
RETURN 1
END
And when I run it with the exec command in Query Analyzer, filling in all parameters with proper values, I get this error message:
Server: Msg 8114, Level 16, State 4, Procedure CheckReOccurences, Line 0
Error converting data type nvarchar to datetime.
Please note Line says 0, when no such line exists. I've tried running every single part separately in QA, and all runs well (the functions work, returns expected code, etc.). What's the problem?
Thanks,
Sarah
View 4 Replies
View Related
Jun 11, 2004
I am having trouble getting this procedure to properly enter the data into a table. It works when I do not add the @ToName info and only ask to insert the AccountID and FromName data. When i add the @ToNamevariable, no data is inserted. I think it might have to do with the select statement. I have two TerritoryID, RegionID, DivisionID, and EmpID because I want this information to be entered for both the FromName and the ToName selected. Does anyone know what my problem is? Id appreciate any help.
CREATE PROCEDURE InsertAllThree
@AccountID char(10),
@FromName nvarchar(50),
@ToName nvarchar(50)
AS
insert into accounttransferstestmike
(AccountID, FromTerritoryID, FromRegionID, FromDivisionID, FromEmpID, ToTerritoryID, ToRegionID, ToDivisionID, ToEmpID)
select Accounts.AccountID, Territories.TerritoryID, Regions.RegionID, Divisions.DivisionID, Employees.EmployeeID, Territories.TerritoryID, Regions.RegionID, Divisions.DivisionID, Employees.EmployeeID
From Accounts, EndoscopySqlUser.Territories INNER JOIN
EndoscopySqlUser.Regions ON EndoscopySqlUser.Territories.RegionName = EndoscopySqlUser.Regions.Region INNER JOIN
EndoscopySqlUser.Employees ON EndoscopySqlUser.Territories.TerritoryID = EndoscopySqlUser.Employees.TerritoryID INNER JOIN
EndoscopySqlUser.Divisions ON EndoscopySqlUser.Regions.Division = EndoscopySqlUser.Divisions.DivisionID
Where (Accounts.AccountID = @AccountID) and (EndoscopySqlUser.Employees.DateLeft IS NULL) AND (EndoscopySqlUser.Territories.TerritoryName=@FromN ame) AND (EndoscopySqlUser.Territories.TerritoryName=@ToNam e)
GO
View 4 Replies
View Related
Oct 31, 2006
When I try to create the stored procedure below, I receive the following error. Can someone please let me know what is wrong with the code? The problem seems to be with the default parameter of getdate(). This is because when I comment the default parameter, it works fine. Please note that I need the @BeginDate parameter to be varchar(10). I cannot have it as datetime.
Msg 156, Level 15, State 1, Procedure test, Line 4
Incorrect syntax near the keyword 'convert'.
Msg 137, Level 15, State 2, Procedure test, Line 8
Must declare the scalar variable "@BeginDate".
/* Stored Procedure*/
Create PROCEDURE test --test
@BeginDate varchar(10) = convert(varchar(10),getdate(),101)
as
select convert(datetime,@BeginDate)
Thanks!
View 9 Replies
View Related
Jan 24, 2008
Hi All,
Appreciate any help that you can offer, I have three tables that need data entered when the user completes a web form, in short the tables are
dbo.JBAClient
Which has
JBCID as PK and other data
dbo.JBAEmployee
Which has
JBEID as PK and JBEClientID as a Foreign Key and other data
dbo.JBAdvert
Which has
JBAID as PK, JBAEmployeeID as Foreign Key , JBAClientID as Foreign Key and other data,
The stored procedure that I've tried to write is supposed to create a new client record and enter all of the relevant data into the client table (store the JBCID) then Create a new Employee Record, insert all relevant data including (JBCID into JBEClientID) and (Store both JBCID & JBEID). Finally create a new advert record and store all of the relevant data including (JBCID as JBAClientID and JBEID as JBAEmployeeID)
The stored procedure that I have written works fine until the last section, where instead of inserting JBCID into JBAClientID and JBEID into JBAEmployeeID, it inserts JBEID into JBAClientID and JBEID into JBAEmployeeID
So inserting JBEID twice and ignoring JBEClientID........
the code is below,---
CREATE PROCEDURE PayPalCLient
@siteid int,
@companyname nvarchar(50),
@address nvarchar(500),
@phone nvarchar(50),
@fax nvarchar(50),
@email nvarchar(225),
@url nvarchar(225),
@companytype nvarchar(50),
@billingcontact nvarchar(50),
@name nvarchar(50),
@AccountType nvarchar(50),
@PASSWORD nvarchar(50),
@AccountLive nvarchar(50),
@EmployeeLevel nvarchar(50),
@adverttitle nvarchar(50),
@description nvarchar(500),
@category nvarchar(50),
@location nvarchar(50),
@payrate nvarchar(50),
@employmenttype nvarchar(50),
@reference nvarchar(50),
@startdate nvarchar(50),
@postfor INT,
@invoiced nvarchar(50),
@notified nvarchar(50),
@ppclient nvarchar(50),
@pppaid nvarchar(50)
AS
Declare @NewID INT
INSERT INTO dbo.JBClient(JBCLSiteID, JBCLName, JBCLAddress, JBCLPhone, JBCLFax, JBCLEmail, JBCLCompanyType, JBCLURL, JBCLAccountType, JBCLAccountlive, JBCLBillingContact)
VALUES (@siteid, @companyname, @address, @phone, @fax, @email, @companytype, @url, @AccountType, @AccountLive, @billingcontact)
DECLARE @NewID2 INT
SELECT @NewID = SCOPE_IDENTITY()
INSERT INTO dbo.JBEmployee(JBEClientID, JBESiteID, JBEName, JBELevel, JBEUsername, JBEPassword, JBEAddress, JBEPhone)
VALUES (@NewID, @siteid, @name, @EmployeeLevel, @email, @PASSWORD, @address, @phone)
SELECT @NewID = SCOPE_IDENTITY()
SELECT @NewID2 = SCOPE_IDENTITY()
INSERT INTO dbo.JBAdvert(JBAClientID, JBAEmployeeID, JBASiteID, JBATitle, JBADescription, JBACategory, JBALocation, JBAPayRate, JBAEmplymentType, JBAReference, JBAStartDate, JBAPostFor, JBAInvoiced, JBANotified, JBAPPClient, JBAPPPaid)
VALUES (@NewID, @NewID2, @siteid, @adverttitle, @description, @category, @location, @payrate, @employmenttype, @reference, @startdate, @postfor, @invoiced, @notified, @ppclient, @pppaid)
Appreciate any help that you can offer, I think the problem has something to do with --
SELECT @NewID = SCOPE_IDENTITY()
SELECT @NewID2 = SCOPE_IDENTITY()
Thanks again
View 3 Replies
View Related
Jul 25, 2006
I have the following stored proceduredrop procedure ce_selectCity;set ANSI_NULLS ONset QUOTED_IDENTIFIER ONGO-- =============================================-- Author: <Author,,Name>-- Create date: <Create Date,,>-- Description: <Description,,>-- =============================================create PROCEDURE ce_selectCity @recordCount int output -- Add the parameters for the stored procedure here --<@Param2, sysname, @p2> <Datatype_For_Param2, , int> = <Default_Value_For_Param2,, 0>AS declare @errNo int -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; -- Insert statements for procedure here select ciId,name from ce_city order by name select @recordCount = @@ROWCOUNT select @errNo = @@ERROR if @errNo <> 0 GOTO HANDLE_ERROR return @errNoHANDLE_ERROR: Rollback transaction return @errNoGoand i was just testing it likeProtected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load db.connect() Dim reader As SqlDataReader Dim sqlCommand As New SqlCommand("ce_selectCity", db.getConnection) Dim recordCountParam As New SqlParameter("@recordCount", SqlDbType.Int) Dim errNoParam As New SqlParameter("@errNo", SqlDbType.Int) recordCountParam.Direction = ParameterDirection.Output errNoParam.Direction = ParameterDirection.ReturnValue sqlCommand.Parameters.Add(recordCountParam) sqlCommand.Parameters.Add(errNoParam) reader = db.runStoredProcedureGetReader(sqlCommand) If (db.isError = False And reader.HasRows) Then Response.Write("Total::" & Convert.ToInt32(recordCountParam.Value) & "<br />") While (reader.Read()) Response.Write(reader("ciId") & "::" & reader("name") & "<br />") End While End If db.close() End SubIt returns ALL ROWS (5 in the table right now). So, recordCount should be 5. (When i run it inside SQL Server (directly) it does return 5, so i know its working there).BUT, its returning 0.What am i doing wrong??EDIT:Oh, and this is the function i use to execute stored procedure and get the readerPublic Function runStoredProcedureGetReader(ByRef sqlCommand As SqlCommand) As SqlDataReader sqlCommand.CommandType = CommandType.StoredProcedure Return sqlCommand.ExecuteReader End Function
View 5 Replies
View Related
Jun 23, 2004
Hi all.
1. I have a stored procedure, the procedure need create new category for forums, each category have their own place (what going first , what going second etc...), it's importent for me that all categories will be in property for them place, so i must read next place from table, and if not then i set it = 0 . But it's seems not working, i getting error.
Can somebody tell me please what wrong ?
ALTER PROCEDURE dbo.CreateCategory
(
@category_name varchar(100)
)
AS
declare @place int
/* setting place to zero */
SET @place = 0
/* trying to get last place and set value into @place */
SET @place = (Select max(category_place) FROM fo_categories)
/* if got nothing from table then setting value of first category */
IF (@place = 0)
set @place = 1
INSERT fo_categories (category_name, category_place)
VALUES(@category_name, @place)
RETURN
Running dbo."CreateCategory" ( @category_name = Public forums ).
Cannot insert the value NULL into column 'category_place', table 'mg_forum.dbo.fo_categories'; column does not allow nulls. INSERT fails.
2. I also would ask what SET NOCOUNT ON/OFF mean and for what i can use it ?
View 2 Replies
View Related
Jan 15, 2004
Hi,
I have a procedure that inserts a record to a table and return the @@Identity as an output parameter.
This table has a trigger that is triggered when a record is inserted and add a new record to other table.
The problem is that the @@Identity returned is totally wrong.
Any ideas?
Thanx in advance.
View 3 Replies
View Related
Dec 28, 2006
So I have been building stored procedures and things were working fine until I hit something that I am sure is incredibly simple to do; however, i have having a hell of a time with it. Here is the code:#############################################ALTER PROCEDURE dbo.GetUserIdForUser @username NVARCHARASBEGINDECLARE @postedbyid UNIQUEIDENTIFIERSET @postedbyid = (SELECT UserIdFROM aspnet_UsersWHERE (UserName = @username))END###Which returns this### Running [dbo].[GetUserIdForUser] ( @username = jason ).No rows affected.(0 row(s) returned)@RETURN_VALUE = 0Finished running [dbo].[GetUserIdForUser].############################################# This is part of a much larger stored procedure, but this is the point of failure in the stored procedure I am trying to build. If anyone can tell me what I am doing wrong I would appreciate it. I have tried a few things that have resulted in different failures. If I remove any references to variables (delete SET @postedbyid = and replace @username with 'jason') I can get it to return a result. If I put @username in though it doesn't work. Here are the examples of those:ALTER PROCEDURE dbo.GetUserIdForUser @username NVARCHARASBEGINSELECT UserIdFROM aspnet_UsersWHERE (UserName = @username)END###Which returns this###Running [dbo].[GetUserIdForUser] ( @username = jason ).UserId -------------------------------------- No rows affected.(0 row(s) returned)@RETURN_VALUE = 0Finished running [dbo].[GetUserIdForUser]. Here is a sanity check to show that the data is in fact in the database:ALTER PROCEDURE dbo.GetUserIdForUserASBEGINSELECT UserIdFROM aspnet_UsersWHERE (UserName = 'jason')END Running [dbo].[GetUserIdForUser].UserId -------------------------------------- No rows affected.(1 row(s) returned)@RETURN_VALUE = 0Finished running [dbo].[GetUserIdForUser]. Anyone have any ideas on what I am doing wrong?
View 13 Replies
View Related
Sep 22, 2005
oConn = New SqlClient.SqlConnection
oConn.ConnectionString = "user id=MyUserID;data source=MyDataSource;persist security info=False;initial catalog=DBname;password=password;"
oCmd = New SqlClient.SqlCommand
oCmd.Connection = oConn
oCmd.CommandType = CommandType.StoredProcedure
oCmd.CommandText = "TestStdInfo"
'parameters block
oParam1 = New SqlClient.SqlParameter("@intSchoolID", Me.ddlSchl.SelectedItem.ToString())
oParam1.Direction = ParameterDirection.Input
oParam1.SqlDbType = SqlDbType.Int
oCmd.Parameters.Add(oParam1)
oParam2 = New SqlClient.SqlParameter("@dob", Convert.ToDateTime(Me.txbBirth.Text))
oParam2.Direction = ParameterDirection.Input
oParam2.SqlDbType = SqlDbType.DateTime
oCmd.Parameters.Add(oParam2)
oParam3 = New SqlClient.SqlParameter("@id", Me.txbID.Text)
oParam3.Direction = ParameterDirection.Input
oParam3.SqlDbType = SqlDbType.VarChar
oCmd.Parameters.Add(oParam3)
oConn.Open()
daStudent = New SqlClient.SqlDataAdapter("TestStdInfo", oConn)
dsStudent = New DataSet
daStudent.Fill(dsStudent) 'This line is highlighted when error happens
oConn.Close()The error I am getting :Exception Details: System.Data.SqlClient.SqlException: Procedure 'TestStdInfo' expects parameter '@intSchoolID', which was not supplied.I am able to see the value during debugging in the autos or command window. Where does it dissapear when it comes to Fill?Could anybody help me with this, if possible fix my code or show the clean code where the procedure called with multiple parameters and dataset filled.Thank you so much for your help.
View 2 Replies
View Related
Feb 19, 2006
Im trying to insert a record in my sql server 2005 express database.The following function tries that and without an error returns true.However, no data is inserted into the database...Im not sure whether my insert statement is correct: I saw other example with syntax: insert into table values(@value1,@value2)....so not sure about thatAlso, I havent defined the parameter type (eg varchar) but I reckoned that could not make the difference....Here's my code: Function CreateNewUser(ByVal UserName As String, ByVal Password As String, _ ByVal Email As String, ByVal Gender As Integer, _ ByVal FirstName As String, ByVal LastName As String, _ ByVal CellPhone As String, ByVal Street As String, _ ByVal StreetNumber As String, ByVal StreetAddon As String, _ ByVal Zipcode As String, ByVal City As String, _ ByVal Organization As String _ ) As Boolean 'returns true with success, false with failure Dim MyConnection As SqlConnection = GetConnection() Dim bResult As Boolean Dim MyCommand As New SqlCommand("INSERT INTO tblUsers(UserName,Password,Email,Gender,FirstName,LastName,CellPhone,Street,StreetNumber,StreetAddon,Zipcode,City,Organization) VALUES(@UserName,@Password,@Email,@Gender,@FirstName,@LastName,@CellPhone,@Street,@StreetNumber,@StreetAddon,@Zipcode,@City,@Organization)", MyConnection) MyCommand.Parameters.Add(New SqlParameter("@UserName", SqlDbType.NChar, UserName)) MyCommand.Parameters.Add(New SqlParameter("@Password", Password)) MyCommand.Parameters.Add(New SqlParameter("@Email", Email)) MyCommand.Parameters.Add(New SqlParameter("@Gender", Gender)) MyCommand.Parameters.Add(New SqlParameter("@FirstName", FirstName)) MyCommand.Parameters.Add(New SqlParameter("@LastName", LastName)) MyCommand.Parameters.Add(New SqlParameter("@CellPhone", CellPhone)) MyCommand.Parameters.Add(New SqlParameter("@Street", Street)) MyCommand.Parameters.Add(New SqlParameter("@StreetNumber", StreetNumber)) MyCommand.Parameters.Add(New SqlParameter("@StreetAddon", StreetAddon)) MyCommand.Parameters.Add(New SqlParameter("@Zipcode", Zipcode)) MyCommand.Parameters.Add(New SqlParameter("@City", City)) MyCommand.Parameters.Add(New SqlParameter("@Organization", Organization)) Try MyConnection.Open() MyCommand.ExecuteNonQuery() bResult = True Catch ex As Exception bResult = False Finally MyConnection.Close() End Try Return bResult End FunctionThanks!
View 1 Replies
View Related
May 1, 2008
i can't seem to get this query to work, it just keep returning nulls with ever values i set . 1 SELECT Bedrooms, Description, Image,
2 (SELECT Location
3 FROM Location_Table
4 WHERE (Property_Table.LocationID = LocationID)) AS Location, LocationID, Price, Price AS PriceMax, PropertyID, Title, TypeID,
5 (SELECT TypeOfProperty
6 FROM Type_Table
7 WHERE (Property_Table.LocationID = TypeID)) AS TypeOfProperty
8 FROM Property_Table
9 WHERE (TypeID = @TypeID OR
10 TypeID IS NULL) AND (LocationID = @LocationID OR
11 LocationID IS NULL) AND (Price >= @MinPrice OR
12 Price IS NULL) AND (PriceMax <= @MaxPrice OR
13 PriceMax IS NULL)
View 7 Replies
View Related
May 14, 2004
This is working:
SELECT...
"CAST(MONTH(Some_Date) as int) as Month, " &_
"CAST(DAY(Some_Date) as int) as Day " &_
"FROM Deceased " &_
"WHERE Active = 1 AND " &_
"MONTH(Some_Date) >= MONTH(GETDATE()) " &_
"ORDER BY Month, Day DESC"
This is NOT:
SELECT...
"CAST(MONTH(Some_Date) as int) as Month, " &_
"CAST(DAY(Some_Date) as int) as Day " &_
"FROM Deceased " &_
"WHERE Active = 1 AND " &_
Month >= MONTH(GETDATE()) " &_
"ORDER BY Month, Day DESC"
it says - Invalid column name 'Month'
Why ? Why ? Why ?
View 3 Replies
View Related
Oct 5, 2004
I'm just learning SQL after using it for about a year now and I'm trying to add a Check constraint to a Social Security Field (See Below) and I can't figure out what is wrong with the syntax. In QA it errors out stating: Line 4: Incorrect syntax near '0-9'.
use Accounting
Alter Table Employees
Add Constraint CK_SNN
Check (SSN Like [0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9])
Any help would be nice. Thanks in advance.
View 2 Replies
View Related
Jan 3, 2005
Hello !! I have just createt a simple login page and reg page, login is working when I make one useraccound directly on to MsSql server, I can login successfully, but the problem is REGISTER PAGE with INSERT code. Here down is the code ov the login.aspx page
Function AddUser(ByVal userID As Integer, ByVal userName As String, ByVal userPassword As String, ByVal name As String, ByVal email As String) As Integer
Dim connectionString As String = "server='(local)'; trusted_connection=true; database='music'"
Dim dbConnection As System.Data.IDbConnection = New System.Data.SqlClient.SqlConnection(connectionString)
Dim queryString As String = "INSERT INTO [users] ([UserID], [UserName], [UserPassword], [Name], [Email]) VALUE"& _
"S (@UserID, @UserName, @UserPassword, @Name, @Email)"
Dim dbCommand As System.Data.IDbCommand = New System.Data.SqlClient.SqlCommand
dbCommand.CommandText = queryString
dbCommand.Connection = dbConnection
Dim dbParam_userID As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_userID.ParameterName = "@UserID"
dbParam_userID.Value = userID
dbParam_userID.DbType = System.Data.DbType.Int32
dbCommand.Parameters.Add(dbParam_userID)
Dim dbParam_userName As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_userName.ParameterName = "@UserName"
dbParam_userName.Value = userName
dbParam_userName.DbType = System.Data.DbType.String
dbCommand.Parameters.Add(dbParam_userName)
Dim dbParam_userPassword As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_userPassword.ParameterName = "@UserPassword"
dbParam_userPassword.Value = userPassword
dbParam_userPassword.DbType = System.Data.DbType.String
dbCommand.Parameters.Add(dbParam_userPassword)
Dim dbParam_name As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_name.ParameterName = "@Name"
dbParam_name.Value = name
dbParam_name.DbType = System.Data.DbType.String
dbCommand.Parameters.Add(dbParam_name)
Dim dbParam_email As System.Data.IDataParameter = New System.Data.SqlClient.SqlParameter
dbParam_email.ParameterName = "@Email"
dbParam_email.Value = email
dbParam_email.DbType = System.Data.DbType.String
dbCommand.Parameters.Add(dbParam_email)
Dim rowsAffected As Integer = 0
dbConnection.Open
Try
rowsAffected = dbCommand.ExecuteNonQuery
Finally
dbConnection.Close
End Try
Return rowsAffected
End Function
Sub LoginBtn_Click(sender As Object, e As EventArgs)
If AddUser(txtUserName.Text, txtUserPassword.Text, txtName.Text, txtEmail.Text) > 0
Message.Text = "Register Successed, click on the link WebCam for login"
Else
Message.Text = "Failure"
End If
End Sub
and here is the error I receive when I try to open this register.aspx page:
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: BC30455: Argument not specified for parameter 'email' of 'Public Function AddUser(userID As Integer, userName As String, userPassword As String, name As String, email As String) As Integer'.
Source Error:
Line 52: Sub LoginBtn_Click(sender As Object, e As EventArgs)
Line 53:
Line 54: If AddUser(txtUserName.Text, txtUserPassword.Text, txtName.Text, txtEmail.Text) > 0
Line 55: Message.Text = "Register Successed, click on the link WebCam for login"
Line 56:
Source File: c:inetpubwwwrootweb_sitemusic
egister.aspx Line: 54
In the DB the fields are added as :
UserID as int
UserName as varchar
UserPassword as varchar
Name as varchar
Email as varchar
and I have TRYED to change from "varchar" on to "text" but I receive same error message.
PLEASE HELP !!!!!!!! this is not first time I get the same errors on the all reg pages :( WHY ? WHAT LINE I HAVE TO EDIT ?
Thank You !!!
Regards
View 2 Replies
View Related
Mar 18, 2005
Hi please lok at this SP I have written and point where am I commiting mistake.
The PROD_ID_NUM field is a varchar field in the actual database.
Any help appreciated.
CREATE PROCEDURE [cp_nafta_dws].[spMXGetProductDetails]
(
@ProductCode Int = null
)
AS
DECLARE @sqlString AS nvarchar(2000)
SET @sqlString = 'SELECT Master.PROD_ID_NUM AS ProductCode,
Master.PROD_DESC_TEXT AS ProductName,
Detail.PiecesPerBox, Detail.Price
FROM cp_nafta_dws.PRODUCT AS Master
INNER JOIN cp_nafta_dws.PRODUCT_MEXICO AS Detail
ON Master.PROD_ID_NUM = Detail.PROD_ID_NUM'
BEGIN
IF NOT (@ProductCode = NULL)
BEGIN
SET @sqlString = @sqlString + ' WHERE Master.PROD_ID_NUM = ' + @ProductCode
END
END
EXEC @sqlString
GO
Thanks
View 11 Replies
View Related
Jul 7, 2005
Hello,
SELECT dbo.tSp.pID, dbo.tLo.oS
FROM dbo.tSp INNER JOIN
dbo.tLo ON dbo.tSp.SpID = dbo.tLo.SpID
WHERE (dbo.tLo.oS = N'[MyText]')
This works without Where and I see MyText available in oS column. Why does it not bring anything when Where is there?
Thanks,
View 3 Replies
View Related
Oct 3, 2005
This code is not updating the database, please help me
SqlCommand UpdCmd; SqlCommand SelCmd; SqlDataAdapter da; DataSet ds = new DataSet();
da = new SqlDataAdapter(); if (!(Conn.State == ConnectionState.Open)) { Conn.Open(); }
SelCmd = null; SelCmd = new SqlCommand("sp_SelectUserInfo",Conn); SelCmd.CommandType = CommandType.StoredProcedure;
oSelCmd.Parameters.Add("@UserID",userid);
da.SelectCommand = oSelCmd;
da.Fill(ds,"UserTab"); oUpdCmd = null; UpdCmd = new SqlCommand("sp_UpdateUserInfo",Conn); UpdCmd.CommandType = CommandType.StoredProcedure;
UpdCmd.Parameters.Add("@UserID",userid); UpdCmd.Parameters.Add("@FirstName",firstName); UpdCmd.Parameters.Add("@LastName",lastName); UpdCmd.Parameters.Add("@Region",region); da.UpdateCommand = UpdCmd; da.Update(ds,"UserTab");
Conn.Close();
View 1 Replies
View Related
Mar 16, 2006
Here is the codeLine 84: Line 85: searchDataAdapter = New System.data.sqlclient.sqldataadapter("SELECT * FROM Inventory Where title=" & title, searchConnection)Line 86: searchDataAdapter.Fill(objItemInfo, "ItemInfo")Line 87: Line 88: Return objItemInfohere is the errorLine 1: Incorrect syntax near '='. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.Data.SqlClient.SqlException: Line 1: Incorrect syntax near '='.Source Error:
View 3 Replies
View Related
Mar 29, 2006
I have a SQL query in my asp.net & c# application. im trying to retrieve the data from two tables where the ID's of the tables match. once this is found i am obtaining the value associated with one of the keys. e.g. my two tables
Event EventCategoryTypeField Type Example Field Type ExampleEventID Int(4) 1 CategoryID(PK)int(4) 1CategoryID(FK)int(4) 1 Type varchar(50) ExerciseType varchar (200) Exercise Color varchar(50) Brown
The CategoryID is a 1:n relationship. my SQL query will retrive the values where the CategoryIDs match and the Tyoe matches as well. once this is found it will apply the associated color with that categoryID (each unique category has its own Color).
my application will read all the data correctly (ive checked it with a breakpoint too and it reads all the different colors for the different ID's) but it wont display the text in the right color from the table. it will just display everything in the first color it comes across.
Im including my code if it helps. can anyone tell me where i am going wrong please?? (the procedures are called on the On_Page_Load method)
private void Load_Events(){///<summary>///Loads the events added from the NewEvent from into a dataset///and then just as with the Holidyas, the events are wriiten to///the appropriate calendar cell by comparing the date. only the ///title and time will be displayed in the cell. other event details///such as, Objective, owner will be shown in a dialog box syle when ///the user hovers over the event.///</summary>
mycn = new SqlConnection(strConn);myda = new SqlDataAdapter("SELECT * FROM Event, EventTypeCategory WHERE Event.CategoryID = EventTypeCategory.CategoryID AND Event.Type = EventTypeCategory.CategoryType", mycn);myda.Fill(ds2, "Events");}
private void Populate_Events(object sender, System.Web.UI.WebControls.DayRenderEventArgs e){///<summary>///This procedure will read all the data from the dataset - Events and then///write each event to the appropriate calendar cell by comparing the date of ///the EventStartDate. if an event is found, the title and time are written///to the cell, other details are shown by hovering over the cell to bring///up another function that will display the data in a dialogBox. once the///event is written, the appropriate color is applied to the text.///</summary>if (!e.Day.IsOtherMonth){foreach (DataRow dr in ds2.Tables[0].Rows){if ((dr["EventStartDate"].ToString() != DBNull.Value.ToString())){DateTime evStDate = (DateTime)dr["EventStartDate"];string evTitle = (string)dr["Title"];string evStTime = (string)dr["EventStartTime"];string evEnTime = (string)dr["EventEndTime"];string evColor = (string)dr["CategoryColor"];
if(evStDate.Equals(e.Day.Date)){e.Cell.Controls.Add(new LiteralControl("<br>"));e.Cell.Controls.Add(new LiteralControl("<FONT COLOR = evColor>"));e.Cell.Controls.Add(new LiteralControl(evTitle + " " + evStTime + " - " + evEnTime));}}}}else{e.Cell.Text = "";}}
View 2 Replies
View Related
Mar 29, 2006
Hi,
Just a quickie... Can anyone see anything wrong with this SQL. I'm using Microsoft SQL Server 2000.
Code:
SELECT * FROM PFP_UserProfiles, Users, PFP_UserSkills, PFP_UserIndustries WHERE PFP_UserSkills.SkillID IN ( '222', '221', '182') AND PFP_UserProfiles.IsPublic = 1;
Cheers
Chris
View 2 Replies
View Related
Mar 11, 2008
Hi everyone.
I'm working on an assignment and I am about to give up. I can't figure out what I'm doing wrong. It seems like I have everything worked out, but when I run the SQL query i've come up with, I get errors regarding INVALID tables.
As far as I can tell, all my tables are valid. Can anyone give me any pointers on what i'm doing wrong **read: I'm not asking for my assignment to be done for me, just asking for help because I am so close to getting the right answer....i think**
Here is what was provided:
http://i47.photobucket.com/albums/f152/hmarandi/problem.gif
Here is the Query I have come up with which gives me errors!
Code:
-- START --
CREATE TABLE dept
(deptnameCHAR(15),
empid CHAR(8),
CONSTRAINT PKdeptname PRIMARY KEY (deptname));
ALTER TABLE dept
ADD CONSTRAINT FKempid FOREIGN KEY (empid) REFERENCES Employee(empid);
-- START --
CREATE TABLE Employee
( empid CHAR(8),
deptname CHAR(15),
empfname VARCHAR(10) NOT NULL,
emplname VARCHAR(10) NOT NULL,
empphone CHAR(15),
empemail VARCHAR(20) NOT NULL,
bossid CHAR(8),
empsalary DECIMAL(9,2) CONSTRAINT CHKEmpsalay Check (empsalary > 5),
CONSTRAINT PKempid PRIMARY KEY (empid),
CONSTRAINT uniqueEmail UNIQUE(empemail) );
-- Add constraint
ALTER TABLE Employee
ADD CONSTRAINT FKdeptname FOREIGN KEY (deptname) REFERENCES dept(deptname);
-- START --
CREATE TABLE POrder
(OrderID CHAR(8),
OrderDatedatetime,
CustIDCHAR(8),
EmpIDCHAR(8)
CONSTRAINT PKOrderIDPRIMARY KEY (OrderID));
-- Add constraint
ALTER TABLE POrder
ADD CONSTRAINT FKCustID FOREIGN KEY (CustID) REFERENCES Customer (CustID);
ALTER TABLE POrder
ADD CONSTRAINT FKEmpID FOREIGN KEY (EmpID) REFERENCES Employee (EmpID);
-- START --
CREATE TABLE Customer
(CustID CHAR(8),
CustNameVARCHAR(15),
BalanceCHAR(8)
CONSTRAINT PKCustIDPRIMARY KEY (CustID));
-- START --
CREATE TABLE OrderItem
(OrderIDCHAR(8),
ProdIDCHAR(8),
QtyCHAR(8)
CONSTRAINT PKOrderIDPRIMARY KEY (OrderID));
ALTER TABLE OrderItem
ADD CONSTRAINT PKProdIDPRIMARY KEY (ProdID)
ALTER TABLE OrderItem
ADD CONSTRAINT FKOrderID FOREIGN KEY (OrderID) REFERENCES POrder (OrderID);
ALTER TABLE OrderItem
ADD CONSTRAINT FKProdID FOREIGN KEY (ProdID) REFERENCES Product(ProdID);
-- START --
CREATE TABLE Product
(ProdIDCHAR(8),
ProdNameVARCHAR(15),
MakerVARCHAR(15),
StockSizeCHAR (6),
PriceCHAR (10)
CONSTRAINT PKProdIDPRIMARY KEY (ProdID));
Any HELP would be greatly appreciated.
Thanks!
View 14 Replies
View Related
Sep 10, 2004
it gives an error saying
"incorrect syntax near update" . can anyone tell me why?
EXEC("update "+@sTable+"
set status='A'
where breakdate < datediff(day,'08/12/1960',getdate())
and clientid=12059
and status ='F'")
View 2 Replies
View Related
Jul 19, 2004
I am trying to created a view and have a need for conditional logic:
Here is what I presently have (not working):
----------------------------------------------------------------------------
IF (ISDATE(COMPLETIONDATE) = 1)
BEGIN
CASE
WHEN DATEDIFF(d, COMPLETIONDATE, RESET.RESET_UNIT.MCD) > (SELECT GREEN FROM RESET.THRESHOLDS WHERE TYPE = 'SCHEDULE') THEN 'GREEN'
WHEN DATEDIFF(d, COMPLETIONDATE, RESET.RESET_UNIT.MCD) < (SELECT GREEN FROM RESET.THRESHOLDS WHERE TYPE = 'SCHEDULE') AND DATEDIFF(d, COMPLETIONDATE, RESET.RESET_UNIT.MCD) > 0 THEN 'YELLOW'
WHEN DATEDIFF(d, COMPLETIONDATE, RESET.RESET_UNIT.MCD) < 0 THEN 'RED'
END AS THRESHOLDSTATUS
END
ELSE
IF (ISDATE(COMPLETIONDATE) = 0)
BEGIN
CASE
WHEN DATEDIFF(d, TARGETCOMPLETIONDATE, RESET.RESET_UNIT.MCD) > (SELECT GREEN FROM RESET.THRESHOLDS WHERE TYPE = 'SCHEDULE') THEN 'GREEN'
WHEN DATEDIFF(d, TARGETCOMPLETIONDATE, RESET.RESET_UNIT.MCD) < (SELECT GREEN FROM RESET.THRESHOLDS WHERE TYPE = 'SCHEDULE') AND DATEDIFF(d, TARGETCOMPLETIONDATE, RESET.RESET_UNIT.MCD) > 0 THEN 'YELLOW'
WHEN DATEDIFF(d, TARGETCOMPLETIONDATE, RESET.RESET_UNIT.MCD) < 0 THEN 'RED'
END AS THRESHOLDSTATUS
END
--------------------------------------------------------------------------
Can someone tell me what I am doing wrong?
Basically I am trying to test to see if "completiondate" is a date and if it is then perform a case operation using it, if it is not a date then I want to perform the case operation using "targetcompletiondate".
Thanks...
View 4 Replies
View Related
May 4, 2008
select * from dbo.Advertisement_Search '%'
Advertisement_Search is a store procedure and i am trying this in ms sql.
Thanks in advance.
View 8 Replies
View Related
Jun 5, 2008
Hello all.
Ive written the following code to check if a foreign key exists, and if it doesnt to add it to a table. The code i have is:
IF NOT EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_tblProductStockNote_tblLookup]') AND parent_object_id = OBJECT_ID(N'[dbo].[tblProductStock]'))
BEGIN
PRINT N'Adding foreign keys to [dbo].[tblProductStock]'
ALTER TABLE [dbo].[tblProductStock] ADD
CONSTRAINT [FK_tblProductStockNote_tblLookup] FOREIGN KEY ([ProductStockNoteType]) REFERENCES [dbo].[tblLookup] ([ID])
IF @@ERROR<>0 AND @@TRANCOUNT>0 ROLLBACK TRANSACTION
IF @@TRANCOUNT=0 BEGIN INSERT INTO #tmpErrors (Error) SELECT 1 BEGIN TRANSACTION END
END
However i keep getting the following error:
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '?'.
Thanks for reading.
View 14 Replies
View Related
Jan 14, 2006
INSERT INTO IS_REGISTERED VALUES
(54907,2715,'I-2001')
Server: Msg 2627, Level 14, State 1, Line 1
Violation of PRIMARY KEY constraint 'PK__IS_REGISTERED__629A9179'. Cannot insert duplicate key in object 'IS_REGISTERED'.
The statement has been terminated.
How do I fix this? I am trying to insert this into the IS_REGISTERED Table.
Student_ID Section_ID Semester
38214 2714 I-2001
54907 2714 I-2001
54907 2715 I-2001
66324 2713 I-2001
IS_REGISTERED (Student_ID, Section_ID, Semester)
albanie
View 7 Replies
View Related
Nov 5, 2007
Hi everybody,
I posted this issue a couple of days ago, but got no solution yet. Anyhow, here is the thing:
"A limited user account is able to see items on the report manager with no permission?"
I have created a local user account on the domain machine where the reports are deployed. This user is not a member of administrator group. It is just a user under the User Group. This user doesn't even have a permission on the Report Manager, not even a browser role. However, this user is able to see the contents of the report manager and also can make changes role assignment under the properties tab in the report manager.
Accourding to my observation so far, any user account created on this domain machine is acting like an admin on the Report Manager, with out being given a permission on the Report Manager. I know something is wrong
Please somebody advise on this
View 5 Replies
View Related
Feb 29, 2008
here i am trying to get the count of both match ((substring(aecprda_1.upc_1,1,11) =
substring(z.upc,1,11) + (AECPRDA_1.product_id = z.vendorcode)... probably AND won't do the trick.
i believe my below query (3) is wrong. what changes should i make to get both the match and continue further.
(3) should be atleast greater than (1) or (2)
1. select count (*) FROM ((select * from aecprda where
AECPRDA.sales_cat_cd in ('02','10') and
(create_dt > '2008-02-17 18:01:38.000' or price_chg_dt > '2008-02-17 18:01:38.000')
) AS AECPRDA_1
left join (zfmt z inner join muzealbums on z.muzenbr=muzealbums.muzenbr) on AECPRDA_1.product_id = z.vendorcode
and z.Vendorname = N'Alliance'
LEFT OUTER JOIN AECMCAT aecmcat_c3
ON AECPRDA_1.mcat_cd3 = aecmcat_c3.Mcat_cd) --- count is 1811 (only the first match)
2. select count (*) FROM ((select * from aecprda where
AECPRDA.sales_cat_cd in ('02','10') and
(create_dt > '2008-02-17 18:01:38.000' or price_chg_dt > '2008-02-17 18:01:38.000')
) AS AECPRDA_1
left join (zfmt z inner join muzealbums on z.muzenbr=muzealbums.muzenbr) on substring(aecprda_1.upc_1,1,11) =
substring(z.upc,1,11) and z.Vendorname = N'Alliance'
LEFT OUTER JOIN AECMCAT aecmcat_c3
ON AECPRDA_1.mcat_cd3 = aecmcat_c3.Mcat_cd) --- count is 2183 (only the second match)
3. select count (*) FROM ((select * from aecprda where
AECPRDA.sales_cat_cd in ('02','10') and
(create_dt > '2008-02-17 18:01:38.000' or price_chg_dt > '2008-02-17 18:01:38.000')
) AS AECPRDA_1
left join (zfmt z inner join muzealbums on z.muzenbr=muzealbums.muzenbr) on ((substring(aecprda_1.upc_1,1,11) =
substring(z.upc,1,11)) and (AECPRDA_1.product_id = z.vendorcode) )
and z.Vendorname = N'Alliance'
LEFT OUTER JOIN AECMCAT aecmcat_c3
ON AECPRDA_1.mcat_cd3 = aecmcat_c3.Mcat_cd) --- count is 1811 (1st & 2nd match.. i expect the count to be higher than 2)
what i am doing wrong here...
View 6 Replies
View Related
Jun 2, 2006
[Column 9] == "00000000" ? NULL(DT_WSTR,10) : RIGHT([Column 9],2) + "/" + SUBSTRING([Column 9],5,2) + "/" + SUBSTRING([Column 9],1,4)
Where destination sql table own as datatype smalldatetime and accept NULLS.
Where Column 9 is defined on the pipeline as [DT_WSTR] with lenght of 10.
Otherwise Column 0 is exactly the same than Column 9 and works fine with this expression:
RIGHT([Column 0],2) + "/" + SUBSTRING([Column 0],5,2) + "/" + SUBSTRING([Column 0],1,4)
[Flat File Source [1]] Error: Data conversion failed. The data conversion for column "Column 9" returned status value 4 and status text "Text was truncated or one or more characters had no match in the target code page.".
View 1 Replies
View Related
Aug 28, 2007
Hi All!
Simple problem, I'm missing something.
I have this at the end of my statement
IF @@ROWCOUNT = 0
EXEC msdb.dbo.sp_send_dbmail
@recipients=N'jrudolf@ikon.com',
@body= @body,
@body_format = 'HTML',
@Subject='NO RECORDS TO DELETE',
@profile_name = 'Ikon'
Else
EXEC msdb.dbo.sp_send_dbmail
@recipients=N'jrudolf@ikon.com',
@body= @body,
@body_format = 'HTML',
@Subject='PLEASE REVIEW RECORDS',
@profile_name = 'Ikon'
END
I'm thinking when it returns 0 rows it should do the first email, else it should do the second email. But it's always doing the second. And I know it's 0 rows, because I'm not getting any results. And I made sure of it.
Thanks!
Rudy
View 9 Replies
View Related