Scalar Func Questions

Jun 6, 2008

Hey Guys, I am creating a scalar function for the first time. I have googled, ck'd your FAQ's, looked 2 text books but cannot find the answer to my questions.
Is the IF statement used in the Scalar function like it is in the stored procedure. In other words does it have to return a Boolean? I want to perform a loop after I call the function, do I have to use a Cursor? Or can I code it like a VB function with a FOR/DO While? Also I can call this UDF from my Stored Proc, right?

Here is a quick synopsis of what I have been assigned to do:
--- Calculate Run Dates
--(start from Previous Saturday subtract 41 days
-- if the 41st day does not fall on a Saturday (day = 7)
-- keep subtracting days until Day=Saturday. Add 6 days to make
-- END date the following Friday)

Thanx,
Trudye

View 11 Replies


ADVERTISEMENT

SUM Func Wont Work HELP!~!~!

Jul 3, 1999

hello,..
please take a look and tell me what's wrong.

*** declare @myfine money
select @myfine=sum(
select fp.total_fine from final_payment fp,inserted i
where fp.member_no=i.member_no and fp.return_complete=0)***
i have final_payment table and everything.I'm creating this syntax in an insert trigger on my final_payment table. will @myfine value be the sum of total_fine where the conditions are true?please help

truly,
JC

View 1 Replies View Related

Missing Leading Zero In Datapart Func If .....

Jun 9, 2003

I use the following code to fill the missing leading zero from datepart sys function. Is there another way simple to get the leading zero if month < 10 and/or if day < 9?
-D

--++++++++++++++++++++++++++++++++
declare @currentYYYYMMDD char(8)
declare @currentYYYY char(4), @currentMM varchar(2), @currentDD varchar(2)
select @currentYYYY = cast(datepart(yyyy, getdate()) as char(4))
select @currentMM = cast(datepart(mm, getdate()) as varchar(2))
select @currentDD = cast(datepart(dd, getdate()) as varchar(2))
print '@currentYYYY: ' + @currentYYYY + ' @currentMM:' + @currentMM + ' @currentDD:' + @currentDD

select @currentMM = case when @currentMM < 10 then '0' + @currentMM
else @currentMM end
select @currentDD = case when @currentDD < 10 then '0' + @currentDD
else @currentDD end
print '@currentYYYY: ' + @currentYYYY + ' @currentMM:' + @currentMM + ' @currentDD:' + @currentDD
select @currentYYYYMMDD = @currentYYYY + @currentMM + @currentDD
print '@currentYYYYMMDD: ' + @currentYYYYMMDD

View 2 Replies View Related

Is It Possible To Use Dynamic Query Inside A Func

Jun 17, 2006

Hi to all,

Is It possible to use dynamic qyery inside a function in sql server.

For Example:

Create function fn_Test
Returns Table
As
Return sp_ExecuteSql 'SELECT * FROM EMP'

Like this.

With regards
Amjath

View 10 Replies View Related

Isnull Func In Coditional Split Tran

Jul 25, 2006

All,

I need to use ISNULL function in a Conditional split transformation. Data will be split based on the ISNULL function. ISNULL( col) can get all the null records, How to get the not null records? ISNULL(col) = €œfalse€? doesn€™t work.

Thanks in Advance

View 6 Replies View Related

User-Defined Func Syntax For Table Return

Oct 30, 2006

Hi all!

I'm trying to use a UDF that returns a table, but I'm not sure of the syntax to invoke it. I've found examples in BOL and on-line like the following:

SELECT * FROM dbo.fn_MyTableFunc( 123.09, 'MyID' )

But I need the input parameter to be obtained from another table. For a very simplistic example, I've got 4 tables (and yes, I know that I can get the results I want for this example without using a UDF, but humor me):

CREATE TABLE tUser (UserID int PRIMARY KEY, UserName varchar(50))
CREATE TABLE tAcctGroup (AcctGroupID int PRIMARY KEY, AcctGroupName varchar(50))
CREATE TABLE tAcct (AcctID int PRIMARY KEY, AcctGroupID int, AcctName varchar(50))
CREATE TABLE tMapUserToGroup (UserID int, AcctGroupID int)
GO

INSERT INTO tUser VALUES (111, 'Me')

INSERT INTO tAcctGroup VALUES (1, 'NY')
INSERT INTO tAcct VALUES (11, 1, 'New York City')
INSERT INTO tAcct VALUES (12, 1, 'Syracuse')

INSERT INTO tAcctGroup VALUES (2, 'GA')
INSERT INTO tAcct VALUES (21, 2, 'Atlanta')
INSERT INTO tAcct VALUES (22, 2, 'Savannah')
INSERT INTO tAcct VALUES (23, 2, 'Augusta')

INSERT INTO tAcctGroup VALUES (3, 'TX')
INSERT INTO tAcct VALUES (31, 3, 'Dallas')
INSERT INTO tAcct VALUES (32, 3, 'Houston')
INSERT INTO tAcct VALUES (33, 3, 'El Paso')
INSERT INTO tAcct VALUES (34, 3, 'San Antonio')

INSERT INTO tAcctGroup VALUES (4, 'CA')
INSERT INTO tAcct VALUES (41, 4, 'Los Angeles')
INSERT INTO tAcct VALUES (42, 4, 'San Francisco')

INSERT INTO tMapUserToGroup VALUES (111,2)
INSERT INTO tMapUserToGroup VALUES (111,4)
GO

CREATE FUNCTION dbo.ufnGetAcctList(@AcctGroupID int) RETURNS @tAcct table (AcctID int, AcctName varchar(50))
AS
BEGIN
INSERT INTO @tAcct
SELECT AcctID, AcctName FROM tAcct WHERE AcctGroupID = @AcctGroupID
RETURN
END
GO

I know that I can do:
SELECT * FROM TestDB.dbo.ufnGetAcctList(4)

But I want the equivalent of:
SELECT AcctID, AcctName FROM tAcct
WHERE AcctGroupID IN (SELECT AcctGroupID FROM tMapUserToGroup WHERE UserID = 111)

Which uses tMapUserToGroup to obtain the AcctGroupID to pass into the function. The results would be:
AcctID AcctName
-----------------------------
21 Atlanta
22 Savannah
23 Augusta
41 Los Angeles
42 San Francisco

Any thoughts?
Thanks in advance for your help.
Cat

View 7 Replies View Related

Code!func To Get Values In Header Only Works In IDE And Not Deployed Report (also Worked Ok In RS2000)

Jul 18, 2007

I have code



Function GetDealCount(reportItems)

return iif(IsNothing(reportItems!txtDetailCountRows.Value), 0, reportItems!txtDetailCountRows.Value)

End Function

Function GetSumNotionalAmount(reportItems)

return iif(IsNothing(reportItems!txtDealSumNotionalAmount.Value), 0, reportItems!txtDealSumNotionalAmount.Value)

End Function



That I am calling from a textboxes in the page header

= Code.GetDealCount(ReportItems) & " Deal(s)"

also

= Parameters!BaseCurrency.Value + " " + Format(Code.GetSumNotionalAmount(ReportItems),"N2").ToString().Replace(",","'")





When I preview the report in VS.NET I get values showing.

When I deploy the report I just get #Error showing.



Also this report used to work fine in RS2000



Does anyone know the cause of this issue?

View 6 Replies View Related

Shortcut To Create @table Def From Table Func?

May 29, 2008

is there a way to create

"CREATE TABLE @table ( blah blah blah...."


from a table value function?

View 1 Replies View Related

Need Help - UDF SQL 00 To Scalar SQL 05

Jul 7, 2006

I'm having trouble with the UDF's I had in SQL 2000 that were migrated to SQL 2005 under the SCALAR FUNCTION item. Before in 2000 you just created the UDF, named it and saved. IN SQL 2005 you create/modify and then have to save it as a .SQL file to a folder. First of all, what folder should it go to so that all can use and secondly, when I do this and run the functions it doesn't work... I need to modify the scalar function and
save it with out saving to a .SQL file. How do I do this or is this the new way to create/modify functions. Any help is much appreciated
thanks

View 6 Replies View Related

Scalar Value

Nov 5, 2006

What is the definition of a scalar value in a relational database?

thx,

Kat

View 3 Replies View Related

Execute Scalar ?

Sep 20, 2007

I'm trying to do something like the code below, but it's saying "specified cast is not valid"
If i change the value returned to an "int", it works fine. My issue is, i'd like to get the value returned with more accuracy than an int as there will be 2 decimal places.protected float getProjectHours(string project)
{string selectCmd = "SELECT SUM(hours) FROM tasks WHERE project=@project";
string strConnection = ConfigurationManager.ConnectionStrings["TimeAccountingConnectionString"].ConnectionString;SqlConnection myConnection = new SqlConnection(strConnection);
SqlCommand myCommand = new SqlCommand(selectCmd, myConnection);myCommand.Parameters.Add(new SqlParameter("@project", SqlDbType.VarChar));myCommand.Parameters["@project"].Value = project;
myConnection.Open();float total = (float)myCommand.ExecuteScalar();
myConnection.Close();
return total;
}

View 6 Replies View Related

Must Declare Scalar @.....

Oct 26, 2007

Hi everyone,
I am getting that infamous message on an INSERT Sql query. I am doing everything right by the looks of it. All variables are either passed in through a custom form, or else declared and initialised  in the body of the script.
I post the relevent code below:
SQLsqlInsertEmail = "INSERT INTO CandidateLogins (SiteID, LoginName, CandidateEmail, DateRegistered) " & _" VALUES (@SiteID, @LoginName, @CandidateEmail, @DateRegistered); SELECT SCOPE_IDENTITY()"Try    sqlSetCandidateEmail.Parameters.Add(New SqlParameter("@SiteID", SqlDbType.Int))    sqlSetCandidateEmail.Parameters("@SiteID").Value = SiteID    sqlSetCandidateEmail.Parameters.Add(New SqlParameter("@LoginName", SqlDbType.VarChar))    sqlSetCandidateEmail.Parameters("@LoginName").Value = userName    sqlSetCandidateEmail.Parameters.Add(New SqlParameter("@CandidateEmail", SqlDbType.VarChar))    sqlSetCandidateEmail.Parameters("@CandidateEmail").Value = email    sqlSetCandidateEmail.Parameters.Add(New SqlParameter("@DateRegistered", SqlDbType.DateTime))    sqlSetCandidateEmail.Parameters("@DateRegistered").Value = DateRegistered    sqlSetCandidateEmail = New SqlCommand(sqlInsertEmail, C4LConnection)
    C4LConnection.Open()    CandidateID = sqlSetCandidateEmail.ExecuteScalar()
Catch Exp As SqlException    lblResults.Visible = True    lblResults.Text = "Unable to Register Jobseeker: " & Exp.MessageFinallyC4LConnection.Close()End Try
All the variables passed into the SQL statement are initialised, with SiteID beign set to '0', rather than Null (none of the fields are Nullable in the database table) and I have checked that the SqlDbType's correspend to the Table Definition 
So far as I can discern, everything is correct and as can be seen, I am not using a stored procedure in this instance, but the script falls over be producing the error message "Must Declare Scalar @SiteID", even though SiteID is declared as Int32 further up in the script.
Any help would be appreciated.

View 8 Replies View Related

UD Scalar Function

Mar 5, 2008

I want to add four fields of a table and place the toatal in a new field.Also I wanna have the average of the fields.

For e.g
I have created a marksheet having four subjects.Now I wanna add the subjects and find the average of the subjects and place them in two different fields in the same table along with the respective names in the table.Pls help.

Thanks in advance.

View 8 Replies View Related

Getdate In Scalar UDF

Sep 25, 2015

My question is: can I use GETDATE function in  scalar UDF as below:

CREATE FUNCTION dbo.GetDateFunction()
RETURNS DateTime
AS
BEGIN
   RETURN GetDate();
END

I have seen this UDF definition in tutorial,but I thought non-deterministic functions can not be used in UDF.

I also looked at two sites to find out but both says differently:

Technet: [URL] ... states that functions that return different values on each call can not be used in UDF.

MSDN: [URL] .... states that  nondeterministic built-in functions can be used in Transact-SQL user-defined functions and in the list of functions GETDATE is listed.

How to verify which one is true?

View 3 Replies View Related

SQL License Questions And Other Questions &&>&&>&&>&&>

Mar 3, 2006

1.    Is it legal  and OK to use a MSDN SQL copy on a production environment or is it strickly for test environments ??

2.   If I own a legal copy of SQL 7 with 5 cals, can I legally use SQL MSDE and have more than 5 people access my SQL server or am I also limited to 5 users as my original ??

 Sorry I am a newbie at this SQL thing.

View 1 Replies View Related

Must Declare The Scalar Variable

Jul 17, 2006

Hello!

I have a aspx page in which I have a Gidview populated by a sqlDataSouce.
This is my code:



<%@ Page Language="VB" AutoEventWireup="false" CodeFile="CostEmployee1.aspx.vb" Inherits="RecursosHumanos_CostEmployee1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server"> <title>Untitled Page</title></head><body> <form id="form1" runat="server"> <div> <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4"
DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None" Style="z-index: 100; left: 0px; position: absolute; top: 0px"> <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> <Columns> <asp:TemplateField> <ItemTemplate> <asp:LinkButton ID="Editar" Text="Editar" runat="server" CommandName="Edit"></asp:LinkButton> </ItemTemplate> <EditItemTemplate> <asp:LinkButton ID="LinkButton1" runat="server" CausesValidation="True" CommandName="Update"
Text="Actualizar" style="color: white"></asp:LinkButton> <asp:LinkButton ID="LinkButton2" runat="server" CausesValidation="False" CommandName="Cancel"
Text="Cancelar" style="color: white"></asp:LinkButton> </EditItemTemplate> </asp:TemplateField> <asp:TemplateField> <ItemTemplate> <asp:LinkButton ID="Apagar" Text="Apagar" runat="server" CommandName="Delete" OnClientClick='return confirm("Tem a certeza que deseja apagar este registo?");' CausesValidation="false"></asp:LinkButton> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Id_CostEmployee" InsertVisible="False" SortExpression="Id_CostEmployee"> <EditItemTemplate> <asp:Label ID="Label1" runat="server" Text='<%# Eval("Id_CostEmployee") %>'></asp:Label> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label1" runat="server" Text='<%# Bind("Id_CostEmployee") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Id_Employee" SortExpression="Id_Employee"> <EditItemTemplate> <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Id_Employee") %>'></asp:TextBox> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label2" runat="server" Text='<%# Bind("Id_Employee") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="FullName" SortExpression="FullName"> <EditItemTemplate> <asp:TextBox ID="textbox5" runat="server" Text='<%# Bind("FullName")%>'></asp:TextBox> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label6" runat="server" Text='<%# Bind("FullName") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="NumEmployee" SortExpression="NumEmployee"> <EditItemTemplate> <asp:TextBox ID="TextBox6" runat="server" Text='<%# Bind("NumEmployee") %>'></asp:TextBox> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label7" runat="server" Text='<%# Bind("NumEmployee") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Period" SortExpression="Period"> <EditItemTemplate> <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("Period") %>'></asp:TextBox> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label3" runat="server" Text='<%# Bind("Period") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="CostHour" SortExpression="CostHour"> <EditItemTemplate> <asp:TextBox ID="TextBox3" runat="server" Text='<%# Bind("CostHour") %>'></asp:TextBox> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label4" runat="server" Text='<%# Bind("CostHour") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Date" SortExpression="Date"> <EditItemTemplate> <asp:TextBox ID="TextBox4" runat="server" Text='<%# Bind("Date") %>'></asp:TextBox> </EditItemTemplate> <ItemTemplate> <asp:Label ID="Label5" runat="server" Text='<%# Bind("Date") %>'></asp:Label> </ItemTemplate> </asp:TemplateField> </Columns> <RowStyle BackColor="#EFF3FB" /> <EditRowStyle BackColor="#2461BF" /> <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" /> <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" /> <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> <AlternatingRowStyle BackColor="White" /> </asp:GridView> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:EuroscutConnectionString %>" SelectCommand="SELECT [HR.CostEmployee].Id_CostEmployee, [HR.CostEmployee].Id_Employee, [HR.CostEmployee].Period, [HR.CostEmployee].CostHour, [HR.CostEmployee].Date, [HR.Employee].FullName, [HR.Employee].NumEmployee FROM [HR.CostEmployee] INNER JOIN [HR.Employee] ON [HR.CostEmployee].Id_Employee = [HR.Employee].Id_Employee"
UpdateCommand="UPDATE [HR.CostEmployee] set Period = @Period, CostHour = @CostHour where Id_CostEmployee = @Id_CostEmployee"
DeleteCommand="DELETE from [HR.CostEmployee] where (Id_CostEmployee = @Id_CostEmployee)"> <UpdateParameters> <asp:Parameter Name="Period" /> <asp:Parameter Name="CostHour" /> <asp:Parameter Name="Id_CostEmployee" /> </UpdateParameters> <DeleteParameters> <asp:Parameter Name="Id_CostEmployee" Type="int32" /> </DeleteParameters> </asp:SqlDataSource> </div> </form></body></html> When I run the page I'm able to edit the row but when I try to delete it gives me the error:

Must declare the scalar variable "@Id_CostEmployee".

I'm tired of "googling" this error, and I've tried all the advices, nothing...
I don't know what is happening here, I have 5 other forms, all simillar and they all work!

Any suggestions, pleeeeaaaase?

Thank's!
Paula

View 10 Replies View Related

Execute Scalar Question

Sep 20, 2006

Im using the following code in my application. Is it redundent to add the "Top 1" to the select or does it help performance? Thanks string strSQL = "SELECT TOP 1 c.CusId " +
"FROM COCUS c " +
"LEFT JOIN CONOTITM n ON c.NotId = n.NotId " +
"WHERE c.CusId NOT IN(SELECT CusId FROM RDK_PROSPECT_LOCK WHERE EmpId <> '" + USER.ID() + "') " +
"ORDER BY n.DateUpdate, c.DateUpdate ASC";


string strCusID = RDK.DATA.ReturnScalar(strSQL);  

View 2 Replies View Related

Must Declare The Scalar Variable

Feb 20, 2007

I'm making an ecommerce web app from following the Apress "Beginning ASP.Net 2 E-commerce with C#" book, and when I implement a stored procedure (I made a mdf DB in the app_Data folder), I get the following message: Must declare the scalar variable @CategoryIDThe code used to obtain this error is below: CREATE PROCEDURE DeleteCategory(@CategoryINT int)ASDELETE FROM CategoryWHERE CategoryID = @CategoryID I get this error with every Stored Procedure I try to implement. What should I do to fix this? In SQL Server 2k5 Management Studio, this problem does not present itself.

View 1 Replies View Related

Must Declare The Scalar Variable

Mar 30, 2007

Hi with the code below I am getting the error
Error inserting record. Must declare the scalar variable "@contractWHERE"
 I removed @contract and it then gave me the error
Error inserting record. Must declare the scalar variable "@zipWHERE"
 I was wondering if some can point me in the right direction for fixxing this
protected void cmdUpDate_Click(Object sender, EventArgs e)
{
//Define ADO.NET Objects.
string updateSQL;
updateSQL = "UPDATE Authors SET ";
updateSQL += "au_id=@au_id, au_fname=@au_fname, au_lname=@au_lname, ";
updateSQL += "phone=@phone, address=@address, city=@city,state=@state, ";
updateSQL += "zip=@zip, contract=@contract";
updateSQL += "WHERE au_id@au_id_original";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(updateSQL, con);
//Add the parameters.
cmd.Parameters.AddWithValue("@au_id", txtID.Text);
cmd.Parameters.AddWithValue("@au_fname", txtFirstName.Text);
cmd.Parameters.AddWithValue("@au_lname", txtLastName.Text);
cmd.Parameters.AddWithValue("@phone", txtPhone.Text);
cmd.Parameters.AddWithValue("@address", txtAddress.Text);
cmd.Parameters.AddWithValue("@city", txtCity.Text);
cmd.Parameters.AddWithValue("@state", txtState.Text);
cmd.Parameters.AddWithValue("@zip", txtZip.Text);
cmd.Parameters.AddWithValue("@contract", Convert.ToInt16(chkContract.Checked));
cmd.Parameters.AddWithValue("au_id_original", lstAuthor.SelectedItem.Value);
//Try to open the database and execute the update
try
{
con.Open();
int updated = cmd.ExecuteNonQuery();
lblStatus.Text = updated.ToString() + " records inserted.";
}
catch (Exception err)
{
lblStatus.Text = "Error inserting record. ";
lblStatus.Text += err.Message;
}
finally
{
con.Close();
}
}
}
 
Many Thanks in advance
 

View 3 Replies View Related

Scalar Variables And Views

Apr 24, 2007

I have a stored procedure that I'm trying too, and must figure out how to convert it to a view. The stored procedure uses two scalar variable for a date range in the WHERE CLAUSE (@StartDate and @EndDate). What can we do in a view if we cannot hard code date ranges? If I use the date field (Paydate) in the view then I cannot get a sum of the Payamt.
I appreciate your help.

View 15 Replies View Related

Problem With Execute.scalar()

Oct 13, 2007

 Hello, I've got the following code: Dim Selected1 Dim cnn As New Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("ConnectionString1").ToString()) Dim SqlCommand As New Data.SqlClient.SqlCommand("SELECT [OKTipp1] FROM [ErsteSchritte] WHERE (User.Name = @UserName)", cnn) SqlCommand.Parameters.Add("@UserName", Data.SqlDbType.VarChar, 30) SqlCommand.Parameters("@UserName").Value = User.Identity.Name cnn.Open() Selected1 = SqlCommand.ExecuteScalar() cnn.Close() MsgBox(Selected1)Unfortunatly, I am given an error message. What did I do wrong?Thanks for any suggestionsRegards 

View 7 Replies View Related

Must Declare The Scalar Variable?

Jun 17, 2013

CREATE PROCEDURE [dbo].[Testing]
@FilteredID VARCHAR (MAX),
@SchoolCode VARCHAR (MAX),

[Code]....

I tried to execute above sproc in SQL Server Management Studio , I received the error: Must declare the scalar variable "@Score1".

View 5 Replies View Related

T-SQL (SS2K8) :: UDF Scalar Value Function

Jun 24, 2015

I build a UDF scalar function like this:

CREATE FUNCTION VerificaAcessoPerfil
(
@codigo INT
)
RETURNS INT

[Code] ....

Curiously when i call my function the same one return always the same value, ex:

Select VerificaAcessoPerfil(2)

the return value is : 698 ??

but if i run the Select statment like this:

SELECT DISTINCT codigo,
(case codigo WHEN 1 THEN 695
WHEN 11 THEN 697 WHEN 2 THEN 211
WHEN 10 THEN 698 WHEN 13 THEN 696
WHEN 4 THEN 1 END)[codigo]
FROM pf (NOLOCK) INNER JOIN pfu (NOLOCK) ON pfu.pfstamp=pf.pfstamp
WHERE codigo IN (1,11,2,10,13,4)
ORDER BY 1 ASC

The value are:

1695
2211
41
10698
11697
13696

View 9 Replies View Related

Must Declare Scalar Variable???

Aug 31, 2006

OK i have my stored procedure all set up and working.. But when i try and add a second variable called @iuser and then after i execute the stored procedure, i get an error saying:-
ERROR
"Must declare scalar variable @iuser"

Here is the code i am using in my stored proc, also my stored proc worked fine before i used a second variable??!

//BEGIN

ALTER PROCEDURE [dbo].[putpending]
(@cuuser nvarchar(1000), @iuser nvarchar(1000))

AS
Declare @sql nvarchar(1000)

SELECT @sql =
'INSERT INTO ' +
@cuuser +
' (Pending) VALUES (@iuser)'

EXECUTE (@sql)

RETURN
//END

And i know my VB.NET code is working but i will put it in anyway:-

//BEGIN

'variables
Dim user As String
user = Profile.UserName
Dim intenduser As String
intenduser = DetailsView1.Rows(0).Cells(1).Text.ToString()

'connection settings
Dim cs As String
cs = "Data Source=.SQLEXPRESS;AttachDbFilename=|DataDirectory|friends.mdf;Integrated Security=True;User Instance=True"
Dim scn As New SqlConnection(cs)
'parameters
Dim cmd As New SqlCommand("putpending", scn)
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("@cuuser", SqlDbType.NVarChar, 1000)
cmd.Parameters("@cuuser").Value = user
cmd.Parameters.Add("@iuser", SqlDbType.NVarChar, 1000)
cmd.Parameters("@iuser").Value = intenduser
'execute
scn.Open()

cmd.ExecuteNonQuery()

scn.Close()
//END

Any ideas why i am getting this error message?

View 10 Replies View Related

Must Declare Scalar Variable @ID

Mar 24, 2007

the following is my code
can anybody rectify my problem that i get when running my application
"Must declare scalar variable @ID"
<asp:GridView ID="GridView1" DataKeyNames="ID" runat="server" AutoGenerateColumns="False" BackImageUrl="~/App_Themes/SkinFile/back1.jpg"
BorderColor="Teal" BorderStyle="Solid" DataSourceID="SqlDataSource1">
<Columns>
<asp:CommandField ButtonType="Button" ShowSelectButton="True" />
<asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID" />
<asp:BoundField DataField="Answers" HeaderText="Answers" SortExpression="Answers" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:YahooConnectionString7 %>"
DeleteCommand="DELETE FROM Answers WHERE (ID = @ID)" InsertCommand="INSERT INTO Answers(ID, Answers) VALUES (@ID, @Answers)"
SelectCommand="SELECT Answers.* FROM Answers" UpdateCommand="UPDATE Answers SET ID = @ID, Answers = @Answers WHERE (ID = @ID)">
<DeleteParameters>
<asp:Parameter Name="ID" />
</DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="ID" />
<asp:Parameter Name="Answers" />
</UpdateParameters>
<InsertParameters>
<asp:Parameter Name="ID" />
<asp:Parameter Name="Answers" />
</InsertParameters>
</asp:SqlDataSource>

View 1 Replies View Related

Must Declare The Scalar Variable

Mar 24, 2008

Following stored proc uses dynamic sql but it gives the error
Msg 137, Level 15, State 2, Line 3
Must declare the scalar variable "@ProjectBenefitID".
though its declared .please. tell the workaround



ALTER PROCEDURE [dbo].[spPMPT_GetBenefit]

@ProjectBenefitID INT,

@OrderBYVARCHAR(40),
-- Parmeters for Paging [Start]
@TotalPages INT OUT ,
@CurrentPageNumber INT OUT ,
@NumberOfRecordsINT = 5, /*PageSize*/
@CurrentPage INT = 0/*PageNumber*/

-- Parmeters for Paging [End]

AS

SET NOCOUNT ON

DECLARE @TMPFLOAT
DECLARE @ErrorMsgID INT
DECLARE@ErrorMsg VARCHAR(200)


----- Paging declarations start
DECLARE @SQLFinal NVARCHAR(4000)
DECLARE @Count INT
DECLARE @SC VARCHAR(4000)
----- Paging declarations end


DECLARE@SelectASVARCHAR(4000)
DECLARE@FromASVARCHAR(4000)
DECLARE@WhereASVARCHAR(4000)
DECLARE@LsOrderBy ASVARCHAR(4000)



-- Initialize vars
SET @SC= ''
SET @From= ''
SET @Where= ''
SET @Select= ''
SET @SQLFinal= ''
SET @Count= 0


IF (@CurrentPage = 0 OR @CurrentPage IS NULL)
BEGIN
--Generate error message
SELECT @ErrorMsg = 'Error occured in Stored Procedure ' + (SELECT name from sysobjects WHERE ID = @@PROCID) + '. The Page Number cannot be zero.'
--Raise error to the user
RAISERROR (@ErrorMsg,16/*severity*/,1/*state*/)
--Return error indicator
RETURN (-1)
END
IF (@NumberOfRecords = 0 OR @NumberOfRecords IS NULL )
BEGIN
--Generate error message
SELECT @ErrorMsg = 'Error occured in Stored Procedure ' + (SELECT name from sysobjects WHERE ID = @@PROCID) + '. Number of records per page cannot be zero.'
--Raise error to the user
RAISERROR (@ErrorMsg,16/*severity*/,1/*state*/)
--Return error indicator
RETURN (-1)
END
IF (@Orderby IS NULL OR @Orderby = '')
BEGIN
--Generate error message
SELECT @ErrorMsg = 'Error occured in Stored Procedure ' + (SELECT name from sysobjects WHERE ID = @@PROCID) + '. The Order by cannot be null.'
--Raise error to the user
RAISERROR (@ErrorMsg,16/*severity*/,1/*state*/)
--Return error indicator
RETURN (-1)
END




CREATE TABLE #TEMP_BENEFIT1
(

AssessBenefitID INT,
ProjectBenefitID INT,
ExpectedQuantity INT,
ExpectedQuality VARCHAR(2000),
Comments VARCHAR(2000)
)

INSERT INTO #TEMP_BENEFIT1 SELECT AssessBenefitID,ProjectBenefitID,
Quantity,Quality,
Comments
FROM PMPT_AssessBenefit
WHERE ProjectBenefitID=@ProjectBenefitID AND AssessFlag='E' --and AssessBenefitID=@IterationID

CREATE TABLE #TEMP_BENEFIT2
(

AssessBenefitID INT,
ProjectBenefitID INT,
ActualQuantity INT,
QtyFileID INT,
QtyFileName VARCHAR(100),
QtyFilepath VARCHAR(100),
ActualQuality VARCHAR(2000),
QuaFileID INT,
QualFileName VARCHAR(100),
QualFilepath VARCHAR(100),
Comments VARCHAR(2000),
refAssessBenefitID INT,
DateasON DATETIME
)

INSERT INTO #TEMP_BENEFIT2 SELECT PAB.AssessBenefitID,PAB.ProjectBenefitID,
PAB.Quantity,pab.qtyFileID,
(SELECT FileName FROM PMPT_Files WHERE FileID = pab.qtyFileID) as QtyFileName,
(SELECT UploadedFilePath FROM PMPT_Files WHERE FileID = pab.qtyFileID) as QtyFilepath,
PAB.Quality,pab.quaFileID,
(SELECT FileName FROM PMPT_Files WHERE FileID = pab.quaFileID) AS QualFileName,
(SELECT UploadedFilePath FROM PMPT_Files WHERE FileID = pab.quaFileID) as QuaFilepath,
PAB.Comments,PAB.refEXPAssessBenefitID,PAB.DateasON
FROM PMPT_AssessBenefit PAB
WHERE ProjectBenefitID=@ProjectBenefitID AND AssessFlag='A'


DECLARE @UNIT VARCHAR(100)
SELECT @UNIT=NAME FROM PMPT_Picklists WHERE PicklistID = (SELECT unitID FROM PMPT_ProjectBenefits WHERE ProjectBenefitID=@ProjectBenefitID)

IF @UNIT IS NULL
SET @UNIT = ''
SET @Select='
DECLARE @UNIT VARCHAR(100)
SELECT @UNIT=NAME FROM PMPT_Picklists WHERE PicklistID = (SELECT unitID FROM PMPT_ProjectBenefits WHERE ProjectBenefitID='+CONVERT(VARCHAR(10),@ProjectBenefitID))+'
SELECTT1.AssessBenefitID, CAST(T1.ExpectedQuantity AS VARCHAR)+'' ''+ @UNIT as ExpectedQuantity,
CAST( T2.ActualQuantity AS VARCHAR)+'' ''+ @UNIT as ActualQuantity, T2.QtyFileID, T2.QtyFileName AS QtyFileName ,T2.QtyFilepath, T1.ExpectedQuality AS ExpectedQuality , T2.ActualQuality AS ActualQuality ,
T2.QuaFileID,T2.QualFileName AS QualFileName ,T2.QualFilepath, T2.COMMENTS,CONVERT(VARCHAR(10),T2.DateasON,103) AS DateasON
FROM#TEMP_BENEFIT1 T1,#TEMP_BENEFIT2 T2
WHERET1.AssessBenefitID = T2.refAssessBenefitID'

View 1 Replies View Related

Using Scalar Functions In Views

Sep 19, 2007

I have a view that contains a complex query. A few of the columnscall a function that returns a specific output. I also use a functionto do a join as well.For example:SELECT l.ID, dbo.getStatus(l.ID) AS statusIDFROM tableName ALEFT OUTER JOIN dbo.Status_LKP s ON dbo.getStatus(l.Leg_ID) =s.statusIDFor 800 records, this query takes about 9 seconds. I realize that foreach record, the function is executed on a per row basis, so I amlooking for alternatives.Does anyone know of other ways to accomplish something of the same?Basically I would like to include UDFs in a query and use those UDFsin the where and join clauses.Thanks

View 2 Replies View Related

Scalar Function Columns

Jul 20, 2005

Is it ill-advised to have columns whose values pull from scalar functionsusing other fields in the record as parameters? For example, if I havecreate table a(iID int primary key)create table b(iID int ,iDetail int,CONSTRAINT PK PRIMARY KEY(iID,iDetail),CONSTRAINT FK FOREIGN KEY (iID) REFERENCES a(iID))Let's say in table b I put price information for each detail and in table aI'd like to put a column that sums these prices for the children of eachrecord. Should I make a computed column that references a function usingiID as a parameter? Or would it be better to create a view for this kind ofpurpose?Regards,Tyler

View 4 Replies View Related

Must Declare The Scalar Variable

Feb 29, 2008



create PROCEDURE [Update_Purged]



AS

Declare @Stg_Purged_union table

(PurgedAccountUnionID int IDENTITY,

Coid char(50),

FacilityId int,

AccountID int,

PatientName char(50),

PatientNo char(50),

PT char(50),

ST char(50),

PurgeDt datetime);

BEGIN

INSERT INTO @Stg_Purged_Union

([Coid]
,null
,null

,[PatientName]

,[PatientNo]

,[PT]

,

,[PurgeDt])

select coid, patientname, patientno, pt, st, purgedt from

[Stg_PurgedAccount]


--updating the facilityid in @stg_purged_account_file_union


update @stg_purged_union set facilityid=(select

facilityid from appfacility as b

where b.unitnum=(select

unitnum from appfacility as c

where c.unitnum=b.unitnum) and @Stg_Purged_Union.coid=b.unitnum)



I am getting the following error.

Must declare the scalar variable "@Stg_Purged_Union"

View 4 Replies View Related

Help Using Asymetric/Symetric Key In A Scalar UDF

Oct 26, 2006

The error message I get is as follows:
Invalid use of side-effecting or time-dependent operator in 'OPEN SYMMETRIC KEY' within a function.
&
Invalid use of side-effecting or time-dependent operator in 'CLOSE SYMMETRIC KEY' within a function.

Here is the code I am trying to implement:

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
ALTER FUNCTION [dbo].[func_GetSIMSPassPhrase]
(
)
RETURNS varchar(30)
AS
BEGIN
OPEN SYMMETRIC KEY sims_sym_Key DECRYPTION BY ASYMMETRIC KEY sims_asym_key
DECLARE @GUID UNIQUEIDENTIFIER
SET @GUID = (SELECT key_guid FROM sys.symmetric_keys WHERE name = 'sims_sym_Key')
DECLARE @passphrase varchar(30)
SELECT @passphrase = (SELECT CAST(DecryptByKey(EncField) AS VARCHAR(30)) FROM tblEncryptTest)
CLOSE SYMMETRIC KEY sims_sym_Key
RETURN @passphrase
END

Anyone have any suggestions? TIA

View 4 Replies View Related

Must Declare The Scalar Variable @RefNo

Jul 25, 2006

ive encounter this problem when i install the application at client side..enfect, i try it on all the PC at my office, i wouldnt encounter this problem..can anyone tell me what is possibly wrong with this?here is the code possible code effectedASPDim myDataset As Data.DataSet = New Data.DataSet        Dim conn As Connection = New Connection("AbnormalControlDataConnString", "P_CreateAbnormalFormSect0")        conn.AddParameter("Pending", Me.Session.Item("UserId"), Data.SqlDbType.Char, 80)        conn.AddParameter("CreateBy", Me.Session.Item("UserId"), Data.SqlDbType.Char, 80)        conn.executeSproc(myDataset)        Me.Session.Add("RefNo", myDataset.Tables(0).Rows(0).Item(0))        conn = Nothing        myDataset = Nothing       gridview1.dataBind() <~~~~~~ i have this gridview bind another sproc                                                                  named[P_GetAbnormalFormSect0)conn.vb    Public Sub New(ByVal con As String, ByVal sprocName As String)        configCon = con        connectionString = System.Configuration.ConfigurationManager.ConnectionStrings(configCon).ConnectionString '        myConnection = New System.Data.SqlClient.SqlConnection(connectionString)        myCommand = New System.Data.SqlClient.SqlCommand()        myCommand.Connection = myConnection        myCommand.CommandType = CommandType.StoredProcedure        myCommand.CommandText = sprocName    End Sub    Public Sub AddParameter(ByVal name As String, ByVal value As String, ByVal type As     SqlDbType, ByVal size As Int16)        myCommand.Parameters.Add(name, type, size)        myCommand.Parameters.Item(myCommand.Parameters.Count - 1).SqlValue = value    End Sub    Public Sub executeSproc(ByRef dataset As Data.DataSet)        myConnection.Open()        myDataSet = New System.Data.DataSet()        myDataSet.CaseSensitive = True        dataAdapter = New System.Data.SqlClient.SqlDataAdapter()        dataAdapter.SelectCommand = myCommand        If Not dataset Is Nothing Then            dataAdapter.TableMappings.Add("asd", "UserInfo")            dataAdapter.Fill(myDataSet)            dataset = myDataSet            myConnection.Close()        Else            myCommand.ExecuteNonQuery()        End If    End SubSprocset ANSI_NULLS ONset QUOTED_IDENTIFIER ONGOALTER PROCEDURE [dbo].[P_GetAbnormalFormSect0]     -- Add the parameters for the stored procedure here    @REFNO CHAR(11) = NULLASBEGIN    -- SET NOCOUNT ON added to prevent extra result sets from    -- interfering with SELECT statements.    SET NOCOUNT ON;    DECLARE    @ErrorCode int    SET @ErrorCode = 0        SELECT * FROM dbo.AFStatusInfo        WHERE dbo.AFStatusInfo.RefNo = @REFNO        IF(@@ROWCOUNT = 0)        BEGIN            SET @ErrorCode = -1        END        IF( @@ERROR <> 0 )        BEGIN            SET @ErrorCode = @@ERROR        END                RETURN @ErrorCodeEND-----------------------------------------------------------------------------------------------set ANSI_NULLS ONset QUOTED_IDENTIFIER ONGOALTER PROCEDURE [dbo].[P_CreateAbnormalFormSect0]     -- Parameters for the stored procedure    @Pending CHAR(80),    @CreateBy CHAR(80) ASBEGIN    -- SET NOCOUNT ON added to prevent extra result sets from    -- interfering with SELECT statements.    SET NOCOUNT ON;        -- @ErrorCode : 0    No Error    --                1    No Data (Ignore when no ResultSet required)    --                2    Parameter not complete    --                3    Conflict with existing data    -- Other error code please refer to @@ERROR code    DECLARE    @ErrorCode int    SET @ErrorCode = 0    DECLARE @Id VARCHAR(11)    DECLARE @Temp VARCHAR(4)    SET @Temp = CAST((SELECT COUNT(*) FROM [AFStatusInfo] WHERE RefNo like ('BS200607%'))AS CHAR(3))    SET @Temp = @Temp + 1000    SET @Id = 'BS'    SET @Id = @Id + CONVERT(CHAR(4),GETDATE(),20)    SET @Id = @Id + CONVERT(CHAR(2),GETDATE(),10)    SET @Id = @Id + SUBSTRING(@Temp,2,3)            INSERT INTO [AFStatusInfo]               (RefNo               ,FlowStatus               ,[Pending]               ,[CreateBy]               ,[DateCreated])            VALUES               (@Id               ,'New'               ,@Pending               ,@CreateBy               ,CONVERT(CHAR(8), GETDATE(), 3))    SELECT @Id AS "RefNo"        IF( @@ERROR <> 0 )        BEGIN            SET @ErrorCode = @@ERROR        END                RETURN @ErrorCode        OnError:            RETURN @ErrorCodeEND----------------------------------------------------------------------------------------------------------------

View 1 Replies View Related

Must Declare The Scalar Variable @recCount.

Aug 21, 2007

Hi,Can somone please tell me why I get the  error 'Must declare the scalar variable "@recCount".' when I execute this Store Procedure? ALTER PROCEDURE dbo.CountTEst AS   SET NOCOUNT ON    DECLARE @sql as nvarchar(100);    DECLARE @recCount as int SET @SQL = 'SELECT @recCount = COUNT(*)   FROM     Pool'   exec sp_executesql @SQL   RETURN @recCount  In this case I expect RETURN value = 4.I've tried various approaches, including adding an OUTPUT parameter to the exec statement, but just can't get the syntax correct. Thanks  

View 14 Replies View Related

Error With NULL Using EXECUTE SCALAR

Dec 11, 2007

I keep getting an error message when I try to place the result of an execute scalar command into a text box.  The msg is:"conversion from 'DBNull' to type 'String' is not valid"
The code I am using is:
 
Dim con as OLEDBConnection
con =NewOleDB connection("Provider = MIcrosoft.JetOLEDB.4.0, Data Source = "c:caps.mdb")
Dim cmd As OLEDBCommand
cmd= NewOLEDBCommand("Select Product from [Inventory Table] Where [Customer ID] = " & grid View1.SelectdValue
texBox1.Text = cmd.ExecuteScalar
 
The code works fine as long as there is a value for the Product.  However if the value in the database is NULL I get an error message: :"conversion from 'DBNull' to type 'String' is not valid". How do I wok around this?
Chas28
 

View 4 Replies View Related







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