Can You Please Correct My Syntax For If Statement In Stored Proc

Nov 23, 2004

I am using @strsql to construct the where condition for a select query.


Can you please correct my syntax.











DECLARE @strsql nvarchar(2000)








IF @ProgNO <> '' then


strsql = WHERE ProgNO = @ProgNO


end if











If @ProjNO <> '' then


if strsql <> '' then


strsql = strsql & " and ProjNO =@ProjNO


ELSE


strsql = wHERE ProjNO =@ProjNO


END IF


END IF











Thank you very much.

View 9 Replies


ADVERTISEMENT

SYNTAX Help, Correct Way To Use LIKE In Statement

Feb 27, 2007

Hi, I'm new to SQL and was wondering if there was an easier way to filter data.

I have two tables -

The first table called Names of Companies has a column named: NAMES

NAMES
XYZ Company
ABC Limited Liability Company
ZZZ Corporation
KKK Inc.
ABC Inc.

The second table called Keywords has a column named: WORDS

WORDS
Company
Limited


I want to search for all NAMES that contain the WORDS in some form

The results should be:

NAMES
XYZ Company
ABC Limited Liability Company

Technically, I can get the results I want by manually typing into the SQL statement all the words that appear in the WORDS column.

SELECT *
FROM [Names of Companies]
WHERE [Names of Companies].Names Like "*Company*" Or ([Names of Companies].Names) Like "*limited*"));

But is there a way that I reference the table Keyword instead of typing into the query statement all the words that appear in the column WORD? I have a lot of words to search for.

Can anyone recommend a better way to do this?

Thanks for all your help!

View 8 Replies View Related

Stored Proc Won't Return Correct Value.

Oct 18, 2007

I am using VS 2006, asp.net and C# to call a stored procedure. I want to return a value from the stored procedure into a variable in my C# code. Currently this is not working for me, and I can not figure out whatthe problem is? Can someone please help me out?
I really don't think the problem is in my stored procedure. I can right click on the stored proc and run it withsuccess. If I trace into the C# code though only a negative one (-1) is returned.
On line 5 I have tried the alternate lines of code but this has not worked for me.
     mySqlCommand.Parameters["@TotalRecords"].Direction = ParameterDirection.Output;     mySqlCommand.Parameters["@TotalRecords"].Direction = ParameterDirection.ReturnValue;
Can someone please help me out. I have spent to much time trying to figure this one out.
// C# code to call stored proc.1  try2   {3     SqlCommand mySqlCommand = new SqlCommand("[GetRecordsAssociatedWithRealtor]", mySqlConnection);4     mySqlCommand.Parameters.Add("@RealtorId", SqlDbType.Decimal, 10).Value = RealtorId;5     mySqlCommand.Parameters["@TotalRecords"].Direction = ParameterDirection.InputOutput;6     mySqlCommand.CommandType = CommandType.StoredProcedure;7     RecordsAssociatedWithRealtor = mySqlCommand.ExecuteNonQuery();8   }
// Stored procedure below.USE [REALTOR]GO/****** Object:  StoredProcedure [dbo].[GetRecordAssociatedWithRealtor]    Script Date: 10/18/2007 13:15:18 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE PROCEDURE [dbo].[GetRecordAssociatedWithRealtor]( @RealtorId int, @TotalRecords int output)AS BEGIN DECLARE @HouseDetailRecords int DECLARE @RealtorRecords int SELECT  @HouseDetailRecords= RealtorId from Realtor where RealtorId=@RealtorId SELECT  @RealtorRecords = RealtorId from ConstructionDetail where RealtorId=@RealtorId SET     @TotalRecords=SUM(@HouseDetailRecords+@RealtorRecords) RETURN  @TotalRecordsEND

View 5 Replies View Related

Correct Syntax For An Update Stored Procedure

Nov 24, 2005

This is probably a very simple question but i would appreciate some helpwith the correct syntax for and update stored procedureI  have created  user form that allows the user to update the name and address fields in a datatable called  customers based on the input value customer ID =  ( datatable/Customers)customerIDI have got this far and then got lost:Create SP_UpdateCustomer(@customerID, @name, @address)As Update customers ( name, address)Where customerID =  @customerID GOCould anyone tell me what the correct sntax should be.many thanksMartin

View 3 Replies View Related

Stored Proc Syntax Error?

Mar 14, 2006

Can anyone see an error here? I am getting a general exception when call this and it is driving me crazy. What am I missing? The error is.....{"Incorrect syntax near 'UpdateStaffDept'." ... Any help is greatly appreciated! Below is the code calling the proc
Thank you!
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
ALTER PROCEDURE [dbo].[UpdateStaffDept]
@Co_Id INT,
@CardNo VARCHAR(50),
@DeptNo VARCHAR(50)

AS
SET NOCOUNT ON

DECLARE
@Error INT

SELECT @Error = @@Error
IF @Error = 0
BEGIN

BEGIN TRANSACTION
UPDATE Staff
SET Dept_No = @DeptNo
WHERE Co_Id = @Co_Id
AND PC_Id IN (SELECT PC_ID FROM PC_Number WHERE PC_Number = @CardNo)

SELECT @Error = @@Error
IF @Error <> 0
BEGIN
ROLLBACK TRANSACTION
RETURN @Error
END
ELSE
COMMIT TRANSACTION

END
 
Dim seldeptno As String
seldeptno = ddlEditPosDept.SelectedValue
Dim cmdChnDept As SqlCommand
cmdChnDept = New SqlCommand("UpdateStaffDept", conEditPos)
cmdChnDept.Parameters.Add(New SqlParameter("@Co_Id", SqlDbType.Int 10))
cmdChnDept.Parameters("@Co_Id").Value = compid
cmdChnDept.Parameters.Add(New SqlParameter("@CardNo", SqlDbType.VarChar, 50))
cmdChnDept.Parameters("@CardNo").Value = lblEditPosCardNo.Text
cmdChnDept.Parameters.Add(New SqlParameter("@DeptNo", SqlDbType.VarChar, 50))
cmdChnDept.Parameters("@DeptNo").Value = seldeptno
cmdChnDept.ExecuteNonQuery()

View 3 Replies View Related

Very Quick Stored Proc Syntax Question

Oct 2, 2006

hi all

i am doing a select statement with a where clause that has a like '%000000334'

what i am trying to acomplish is to write the where clause with a variable

where trancmt like '%@iInvcNo%'

what would be the correct way to write this?

thanks
tibor

View 2 Replies View Related

I Am Trying To Use A Stored Proc To Page Thru Table But It Is Saying Incorrect Syntax Near GO

Aug 24, 2007

Can anyone helpCREATE PROCEDURE PagedResults_New
(@startRowIndex int,
@maximumRows int
)
AS
 
--Create a table variable
DECLARE @TempItems TABLE
(ID int IDENTITY,
ShortListId int
)
-- Insert the rows from tblItems into the temp. table
INSERT INTO @TempItems (ShortListId)
SELECT Id
FROM shortlist SWHERE Publish = 'True' order by date DESC
 
-- Now, return the set of paged records
SELECT S.*, C.CategoryTitleFROM @TempItems t
INNER JOIN shortList S ON
t.ShortListId = S.Id
 WHERE ID BETWEEN @startRowIndex AND (@startRowIndex + @maximumRows) - 1
GO

View 1 Replies View Related

Incorrect Syntax Near The Keyword CONVERT When The Syntax Is Correct - Why?

May 20, 2008

Why does the following call to a stored procedure get me this error:


Msg 156, Level 15, State 1, Line 1

Incorrect syntax near the keyword 'CONVERT'.




Code Snippet

EXECUTE OpenInvoiceItemSP_RAM CONVERT(DATETIME,'01-01-2008'), CONVERT(DATETIME,'04/30/2008') , 1,'81350'




The stored procedure accepts two datetime parameters, followed by an INT and a varchar(10) in that order.

I can't find anything wrong in the syntax for CONVERT or any nearby items.


Help me please. Thank you.

View 7 Replies View Related

Like Statement Is SQL Stored Proc

May 29, 2008



i have a sp with the following sql statement inside it

select
name
from
customers
where
name
like
@ShopperName + '%'
--------------------------
If I paas to the store proc '%123' as the value for shoppername it will return all values in the table. Instead I should get all record starting with %123.
What could be a perfect solution

View 1 Replies View Related

Problem With If Statement In Stored Proc

Nov 7, 2006

Hi All,
I'm haveing problems with a simple if statement within a stored proc. Here is a snippet of the stored proc
    SELECT *    FROM [tbl_jobs], [tbl_users]      WHERE tbl_jobs.companyid = tbl_users.id     IF @industry = 31     BEGIN    AND industry = @industry     END
 The error message i get from enterprise manager is:
Error 156: Incorrect syntax near the keyword 'AND'
If i remove the if statement and select and select an 'industry' value other than 31 the it works fine.
Thanks

View 6 Replies View Related

Building A Sql Statement In A Stored Proc

May 12, 2008

Hi All,
What i'm trying to do is build a dynamic query where the like clause is the variable bit of the query. What I've done is to create 4 varchar variables of length1000, and a variable to hold the result of the concatenated variables, which is defined as length of 4000. I've checked the length of the resultant query and its comes in at arount the 450 charcter lenght, but when I run the stored proc it truncates the @varfull around the point of the first % sign.
I've tried various ways to create this query and it always truncated around the point of the % sign.
Am I doing this right? can anyone point me in the right direction on how to do this with a sql statement, it works fine for text strings!
Here's part of the code, I create the content of @var3 in a loop based on a string of words passed into the stored proc.
Thanks for any help on this!
regrads
davej
@var1 = 'SELECT COUNT(d.item_id) AS Expr1, d.item_id FROM tp_index_details AS d INNER JOIN tp_index ON d.idx_id = tp_index.idx_id '@var2 = 'WHERE (d.idx_id IN (SELECT idx_id FROM tp_index AS i WHERE (item_Text LIKE'
@var3 = ''%london%' OR item_Text LIKE '%solicitor%''
@var4 = ' ) AND (subscription_id = 1000))) GROUP BY d.item_id ORDER BY d.item_id DESC'
@varfull = @var1+@var2+@var3+@var4
 

View 11 Replies View Related

Multiple Select Statement In A Stored-proc?

Mar 1, 2005

I am using SQL sever 2k and C#.

There is a stored-procedure that it has multiple select statements as returned result set. How can I use SqlCommand.ExecuteReader to get all result set?

What if the multiple select statements is " FOR XML", how can I set all xml using ExecuteXmlReader?

I tried to use ExecuteReader or ExecuteXmlReader, but seems that I can only get back the result set of the first select statement, all others are messed up.

stored procedure example: NorthWind database:

SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

Create PROCEDURE dbo.getShippersAndEmployeesXML
AS


select * from Shippers for xml auto, elements
select * from Employees for xml auto, elements

RETURN @@ERROR

GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO


C# code example:

//set connect, build sqlcommand etc

XmlTextReader reader = (XmlTextReader)command.ExecuteXmlReader();
StringBuilder sb = new StringBuilder();
while(reader.Read()) sb.Append(reader.ReadOuterXml());



Thanks for your help.

View 2 Replies View Related

Select Statement Returns Null In Stored Proc

Feb 22, 2006

If I run this statement in Query Analyzer, it properly returns 1for my testing table. But if I put the statement into a storedprocedure, the stored procedure returns NULL. What am I doingwrong? I suspect it may be related to how I defined the parametersfor the stored procedure. Perhaps my definition of TableName andColumnName don't match what COLUMNPROPERTY and OBJECT_ID expect toreceive, but I don't know where to look for the function declarationsfor those. Any pointers would be appreciated.Select statement:SELECT COLUMNPROPERTY(OBJECT_ID('Table1'), 'TestID', 'IsIdentity') ASIsIdentityTable definition:CREATE TABLE [dbo].[Table1] ([TestID] [numeric](18, 0) IDENTITY (1, 1) NOT NULL ,[Description] [varchar] (50) COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL) ON [PRIMARY]Stored Procedure definition:CREATE PROCEDURE spTest(@TableName varchar,@ColumnName varchar)AS SELECT COLUMNPROPERTY(OBJECT_ID(@TableName), @ColumnName,'IsIdentity') AS IsIdentity

View 2 Replies View Related

Stored Proc Call, 'table Name' As String, And T-sql Statement

Jun 16, 2006

I need to write a storedproc that receives the name of a table (as a string) and inside the stored proc uses select count(*) from <tablename>. The problem is the passed in tablename is a string so it can't be used in the select statement. Any ideas how I can do what I want?



TIA,

barkingdog



View 1 Replies View Related

How Do Use Stored Proc Passing Parameter From Table In Selcet Query Statement

Aug 8, 2002

i want to use store procedure in select query statement. store procedure will take two parameters from table and return one parameter.

for example i want to use

select p1 = sp_diff d1,d2 from table1

sp_diff is stored procedure
d1,d2 value from table
p1 is the returning value

View 1 Replies View Related

Same Statement Executes 10 Times Faster As Raw Sql In Query Analyzer Then In A Stored Proc

Aug 15, 2007



Hi,


I apologize for the long post but I am trying to give as much information as I can about the steps I've taken to troubleshoot this.


We have a stored procedure that builds a sql statement and executes it using the Execute command. When I execute the stored procedure through query analyzer it takes close to 5 seconds to execute. When I print out the exact same statement and execute it directly in query analyzer as "raw sql", it takes 0.5 seconds - meaning it takes 10 times longer for the code to execute in the stored proc. I altered the stored proc to execute the printed sql instead of building but it still takes the full 5 seconds and there were no changes in the execution plan. This makes me confident that the issue is not caused by the dynamic sql. I've used with recompile to make sure that the stored procedure caches the most recent execution plan. When I compare the execution plans, the stored proc uses a nested loop whereas the raw sql statement uses a hash join. Seeing that, I added the hash hint to the stored proc and doing so brought down the execution time down from 5 secs to 2 secs but still the raw sql statement uses a clustered index whereas the stored proc uses a non-clustered index and that makes the statement 4 times slower. This proves how efficient clustered indexes are over non-clustered ones, but it doesn't help me since, as far as I know, I can't force SQL Server to use the clustered index.


Does anyone know why sql server is generating such an inefficient execution plan for the stored proc compared to the execution plan that it generates when executing the raw sql statement? The only thing I can think of is that some stats are not updated and that somehow throws off the stored proc. But then again, shouldn't it affect the raw sql statement?


Thank you,


Michael Tzoanos

View 4 Replies View Related

Correct Syntax

Sep 25, 2006

HelloI have having trouble displaying some simple columns in ascending order.I know that the database is populated and I can get the more complex code to work if I display like this: SELECT FName, LName, Town, '<a href="' + url + '">' + Site + '</a>' as LinkFROM Names_DBWHERE FName = 'Tom' And url like 'http:%'ORDER BY LName ASCBut I need a simpler view but I can't get it to workI  have tried this:SELECT FName, LNameFROM Names_DBORDER BY  LName ASCAnd thisSELECT FName, LNameFROM Names_DBORDER BY  LName ASC; And This:SELECT FName, LNameFROM Names_DBORDER BY  LName 'ASC' What is wrong with this syntax?ThanksLynn

View 2 Replies View Related

What Is The Correct Syntax For Anything

Mar 15, 2007

I have a query and I need to check to see if a field is occupied, i.e., it can have anything in it, i just want to see if something is there... this is what I want, but of course, anything isn't the right word here...

and (r.id = 'anything')

View 7 Replies View Related

Correct Syntax

Feb 25, 2008

Hi.

This is a Stored proc I am working on
I dont know much about stored procs.
This is what I am trying to achieve
The proc takes two input parameter and returns one outparameter.

This is what I have

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[GetNextAction]

(
@Code char(10),
@Track varchar(30),
@NextAction ntext output
)
AS
BEGIN

SET NOCOUNT ON;
Declare @ID int;
@ID = Select Sequence from [dbo].[Track] where Code=@Code;
Declare @nextCode varchar;
@nextCode= Select Code from [dbo].[Track] where sequence =(@ID+1);
@NextAction= Select nextAction from [dbo].[CaseStage] where Code=@nextCode;
return @NextAction;


END
GO

I guess you can understand what I am trying in the proc but the rules and syntax are wrong. Please help me with this.
Thanks

View 4 Replies View Related

Please Correct Syntax

Dec 3, 2006



hi there

RS2005 - Layout tab

I have a field that says

txtTrackerTrue=Sum(Iif ((Fields!Tracker.Value = Fields!RecvdBy.Value), 1,0 ))

I want another field that says

txtAllTrue=Sum(Iif ((Fields!Tracker.Value, ClosedBy.Value = Fields!RecvdBy, 1,0 ))

obviously this is going to error

how would I do this please

thanks

View 19 Replies View Related

What Is Correct Syntax

Oct 19, 2007

select CONVERT(VARCHAR, stdate, 'YYYY') startyear
from tbl_emp


i want output : 2007



How can i get?

View 5 Replies View Related

Correct InsertParameters Syntax

Jan 29, 2008

If someone can show me the correct syntax for the right side of the code below, I'd appreciate it.
srcMoreInfo.InsertParameters("Address").DefaultValue =       DirectCast(cuwMoreInfo.FindControl("txtAddress"), TextBox).Text 

View 11 Replies View Related

Is Syntax Is Correct ? URGENT

Jun 21, 2000

CREATE PROCEDURE test1
@spname nvarchar(20),
@tblname nvarchar(50)
AS

declare @sqlrun varchar(8000)

set @sqlrun = "CREATE PROCEDURE @sp_name AS CREATE TABLE @tblname
(MsdsId [nvarchar] (5),
IngredId [nvarchar] (2),
Agency [nvarchar] (10),
AgencyText [nvarchar] (4) ,
nName [nvarchar] (40))"

eXEC sp_ExecuteSql @sqlrun

WHATS WRONG IN THIS CODE ?
---------------------------------
PS: I'm getting this error:
-------------------------------

Server: Msg 214, Level 16, State 2, Procedure sp_executesql, Line 7
Cannot convert parameter '@statement' to ntext/nchar/nvarchar data type expected by procedure.

View 2 Replies View Related

Correct Syntax For Dtsrun

May 18, 2006

Somehow I'm not getting dtsrun to work.

The server is local

The name of the package is ImportHosttrncs. It is saved under Local Packages.

There is no password.

Is this syntax correct?

dtsrun /Slocalhost /PImportHosttrncs

View 1 Replies View Related

Correct Syntax For IF EXISTS

Apr 11, 2008

What is the correct syntax for dropping a column if it exists?

Cant seem to get it to work. This is SQL 2005 if it makes a difference.





ALTER TABLE Reports_PI_Recent

IF EXISTS (DROP COLUMN RollingAverage )

View 3 Replies View Related

Correct Syntax For Parameters When Creating SQL Job

Dec 30, 2007

I'm trying to create a SQL job in SQL Server and am a little unclear about the formatting.Here's a snippet from the stored procedure that creates the job:CREATE PROCEDURE [dbo].[spArchive]     @DB            varchar(30),    @Date        DateTimeAS EXEC msdb.dbo.sp_add_jobstep @job_name = 'ArchiveIncentives'     , @step_id = 1    , @step_name = 'ArchiveAHD'    , @subsystem = 'TSQL'    , @command = 'spArchiveAHD ''@Date'''    , @on_success_action = 3     , @on_fail_action = 2     , @database_name = '@DB'     , @retry_attempts = 1   In this case, the job will be calling this stored procedure:CREATE PROCEDURE [dbo].[spArchiveAHD] (    @dtArchiveBefore DateTime)AS I'm unclear about these lines:    @command = 'spArchiveAHD ''@Date'''    @database_name = '@DB'   Do they look correct to you or should I drop some/all of the apostrophes?Robert W. 

View 5 Replies View Related

Is There Any Correct Syntax For ParameterDirection.Input ?

Apr 3, 2008

 I try to call the storeproc to perform task by allowing only input 6 of length. The syntax over here might not be relevant, im seeking for correct syntax.
 webform
Dim connString2 As String = _ConfigurationManager.ConnectionStrings("Local_LAConnectionString1").ConnectionString Using myConnection2 As New SqlConnection(connString2)
Dim test01 As IntegerDim myPuzzleCmd2 As New SqlCommand("GetRandomCode", myConnection2)
myPuzzleCmd2.CommandType = CommandType.StoredProcedure
Dim retLengthParam As New SqlParameter("@Length", SqlDbType.TinyInt, , 6)                 < --------   allow 6 letters in length to be input   
retLengthParam.Direction = ParameterDirection.InputmyPuzzleCmd2.Parameters.Add(retLengthParam) Dim retRandomCode As New SqlParameter("@RandomCode", SqlDbType.VarChar, 30)
retRandomCode.Direction = ParameterDirection.Output
myPuzzleCmd2.Parameters.Add(retRandomCode)
TryDim reader2 As SqlDataReader = myPuzzleCmd2.ExecuteReader()
myPuzzleCmd2.ExecuteNonQuery()
Catch ex As Exception Response.Write("sp value : " & retRandomCode.Value)
Dim iRandomCode(1) As StringReDim Preserve iRandomCode(1)
iRandomCode(1) = Convert.ToString(retRandomCode.Value)myPuzzleCmd2 = Nothing
Session.Remove("RandomCode") HttpContext.Current.Session("RandomCode") = iRandomCode(1) Response.Write(Session("RandomCode"))
Finally
myConnection2.Close()
End Try
End Using
 
StoredProcedure ALTER PROC [dbo].[GetRandomCode]
@Length TINYINT,
@RandomCode VARCHAR(30) OUTPUT
ASDECLARE
@Chars2BUsed VARCHAR(30),
@LookAt TINYINT,
@iCnt INT,
@CharFound CHAR(1)
 
SELECT @Chars2BUsed ='ABCDEFGHJKLMNPQRTUVWXYZ2346789'
SELECT @RandomCode = ''SELECT @iCnt = 1 WHILE @iCnt<=@Length
BEGINSELECT @LookAt = FLOOR((RAND()*LEN(@Chars2BUsed))) + 1
SELECT @CharFound = SUBSTRING(@Chars2BUsed, @LookAt, 1)IF CHARINDEX(@CharFound, @RandomCode)=0
BEGINSELECT @RandomCode = @RandomCode + @CharFound
SELECT @Chars2BUsed = REPLACE(@Chars2BUsed, @CharFound, '')SELECT @iCnt = @iCnt + 1
END
END

View 2 Replies View Related

Correct Syntax For This Select In SQL Server?

Jun 22, 2007

This (demo) statement is fine in Access, and so far as I can see, shouldbe OK in SQL Server.But Enterprise Manager barfs at the final bracket. Can anyone helpplease?select sum(field1) as sum1, sum(field2) as sum2 from(SELECT * from test where id < 3unionSELECT * from test where id 2)In fact, I can reduce it to :-select * from(SELECT * from test)with the same effect - clearly I just need telling :-)cheers,Jim--Jima Yorkshire polymoth

View 4 Replies View Related

Can You Trace Into A Stored Proc? Also Does RAISERROR Terminate The Stored Proc Execution.

Feb 13, 2008

I am working with a large application and am trying to track down a bug. I believe an error that occurs in the stored procedure isbubbling back up to the application and is causing the application not to run. Don't ask why, but we do not have some of the sourcecode that was used to build the application, so I am not able to trace into the code.
So basically I want to examine the stored procedure. If I run the stored procedure through Query Analyzer, I get the following error message:
Msg 2758, Level 16, State 1, Procedure GetPortalSettings, Line 74RAISERROR could not locate entry for error 60002 in sysmessages.
(1 row(s) affected)
(1 row(s) affected)
I don't know if the error message is sufficient enough to cause the application from not running? Does anyone know? If the RAISERROR occursmdiway through the stored procedure, does the stored procedure terminate execution?
Also, Is there a way to trace into a stored procedure through Query Analyzer?
-------------------------------------------As a side note, below is a small portion of my stored proc where the error is being raised:
SELECT  @PortalPermissionValue = isnull(max(PermissionValue),0)FROM Permission, PermissionType, #GroupsWHERE Permission.ResourceId = @PortalIdAND  Permission.PartyId = #Groups.PartyIdAND Permission.PermissionTypeId = PermissionType.PermissionTypeId
IF @PortalPermissionValue = 0BEGIN RAISERROR (60002, 16, 1) return -3END 
 

View 3 Replies View Related

Correct Syntax For ADO.net Recordset's Select Method.

Feb 17, 2006

I have a interger stored in x.

I want to use x in a SELECT statement like so :

SELECT * from aTable WHERE A_Column = x

This select statement is then assigned to and passed as a string like :

sql = "SELECT * from aTable WHERE A_Column = x"

How does the x get interpreted correctly ?

View 1 Replies View Related

Correct Syntax Using Variables Inside SQL Queries (SqlCommand)

Mar 30, 2008

I have a test page where I'm using SqlConnection and SqlCommand to update a simple database table (decrease a number).
I'm trying to figure out how to make a number in the database table to decrease by 1 each time a button is being pressed. I know how to update the number by whatever I want to, but I have no idea what the correct syntax is for putting variables inside the query etc. Like "count -1" for instance.
The database table is called "friday" and the one and only column is called "Tickets".
Here's the code behind the button:protected void Button1_Click(object sender, EventArgs e)
{SqlConnection conn;
conn = new SqlConnection("Data Source=***;Initial Catalog=***;Persist Security Info=True;User ID=***;Password=***");
conn.Open();int count = -1;
 SqlCommand cmd = new SqlCommand("select Tickets from friday", conn);
count = (int)cmd.ExecuteScalar();if (count > 0)
{
 string updateString = @"
update friday
set Tickets = 500" ;   <------ Here I want to set Tickets like "current count -1"SqlCommand cmd2 = new SqlCommand(updateString);
cmd2.Connection = conn;
cmd2.ExecuteNonQuery();
}
else
{
}
conn.Close();
}

View 3 Replies View Related

Correct Syntax For Query Using Osql.exe In MSDE Setup

Nov 10, 2003

I have the following .bat file that I call to register users to my MSDE instance...

echo osql -E -S %COMPUTERNAME%OfficiumInstance -Q "sp_grantlogin '" + %COMPUTERNAME% + "ASPNET'"
echo osql -E -S %COMPUTERNAME%OfficiumInstance -d Officium -Q "sp_grantdbaccess '" + %COMPUTERNAME% + "ASPNET'"
echo osql -E -S %COMPUTERNAME%OfficiumInstance -d Officium -Q "sp_addrolemember 'db_owner', '" + %COMPUTERNAME% + "ASPNET'"

My question is how do I correctly append %COMPUTERNAME% as a string to

I have tried using + signs...

"sp_grantlogin '" + %COMPUTERNAME% + "ASPNET'"

But that doesn't work.
I have looked for .bat file tutorials on the web but can't find the correct way to do this.

Greg

View 1 Replies View Related

Integration Services :: Correct Syntax To Access A Variable

Sep 30, 2015

I am having trouble finding the correct syntax to access a variable. I have a variable defined in the Variables window: The variable name is formatedDate. The DataType is String.

I am successfully setting the value of the variable in a Execute SQL Task. The SQL is as follows:

SELECT LEFT(CONVERT(VARCHAR, MAX(ReportDate), 120), 10) as formatedDate
from DimReportDates

The Result Set is set to “Single Row” and properly set up. 

No problem so far. I can see with a watch that the variable has the correct value, something like:

‘2015-09-30’

Now, in a subsequent step, a Data Flow Task, I want to access the variable. Actualy it is in the SQL statement of a OLE DB source in the Data Flow… I have the following:

Declare @sDate smalldatetime
SELECT @sDate = xxxxx

I have tried several things substituting xxxxx above, but nothing seems to work. One variation was

 @[User::formatedDate])

 Another was

((DT_WSTR, 10) @[User::formatedDate]).

I think I’m close, but just can’t get it. What is the correct syntax.

View 4 Replies View Related







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