Declared Hard Coded Variables
Jun 3, 2015
declare @StartTime nvarchar(10)= '12:00'
declare @EndTime nvarchar(10)= '12:45'
declare @Diff time(1) = cast(@EndTime as datetime) - cast(@StartTime as datetime)
How to I use Column names instead of Hard coding variables - e.g. '12:00'
View 9 Replies
ADVERTISEMENT
Dec 12, 2001
I thought a stored procedure was taking much too long to complete. So, I moved the main query to Query Analyzer and found that when I substituted actual values for variables that my SELECT statement ran in seconds. Just to test, I created DECLARE statements, set the variables equal to the same values, re-ran the SELECT statement and it took over a minute. Even the Execution Plan was much different. Any suggestions?
View 4 Replies
View Related
Feb 8, 2007
Is it possible to force parameters into the reports so enabling me to force a user id value into every report that is picked up from the list. The user ID is a system value and I don't want end users having any knowledge of it?
Cheers
Darren
View 7 Replies
View Related
Jun 6, 2007
Me.SqlConnection1.ConnectionString = "workstation id=""XXXXXXXX"";packet size=4096;user id=XX;data source=""XXXXXXX"";persi" & _
"st security info=True;initial catalog=manufacturing;password=XXXXX"
What excatly is this statement doing it looks to be creating a trusted connection to a certain workstation?
View 3 Replies
View Related
Feb 24, 2004
Hi there,
The postage and packing scheme being used at the site I'm working on depends on the customer's location.
If they're in the UK they get once scheme and if they're in Ireland they get another. Furthermore, if they're anywhere else they get another scheme.
A customer's country is indicated by a 'countryID' stored in the main customer row in the database. (This ID references a country in the Countries table.)
Thus, I was wondering if it is acceptable to hard code the country pk of the UK and Ireland into the formular which works out the postage and packing?
At present, for a similar issue, I've even hard coded the the pk of UK and Ireland into some Javascript running at the client.
Is it fair design to work with a hard coded pk like this?
Cheers,
View 1 Replies
View Related
Mar 27, 2001
Hello I was hoping somebody out there could help me …..
We have a hard-coded application which uses the Sa account with no password. We want to add password to Sa – but when we do get users/DBAs calling us saying the application does not work.
How can we add password to Sa and get the application to work - unfortunately we do not have scripts for the application or know of the whereabouts of the developers.
Any suggestions/ideas – will be greatly appreciated
Cheers
Khalid
View 2 Replies
View Related
Jul 23, 2005
Dear Reader ,There are some details <facts>, which can be stored (Hard coded) in exe.example: Measurement Units and their relations.Now I want to print the list of those Measurement Units and Relationships between them.Can we print them directly , without bringing them into Database?Can we use them and make reports merging details from the Database?Am using SQL 2000 and VB.Net 2003SuryaPrakash Patel--Message posted via http://www.sqlmonster.com
View 1 Replies
View Related
Nov 6, 2014
I want to be able to return the rows from a table that have been updated since a specific time. My query returns results in less than 1 minute if I hard code the reference timestamp, but it keeps spinning if I load the reference timestamp in a table. See examples below (the "Reference" table has only one row with a value 2014-09-30 00:00:00.000)
select * from A where ReceiptTS > '2014-09-30 00:00:00.000'
select * from A where ReceiptTS > (select ReferenceTS from Reference)
View 5 Replies
View Related
Jan 10, 2007
Hi. I've looked all over MSDN, newsgroups and the web but I can't find the answer to a problem that I am having.
The application that I am working on used both transactional and merge replication. I want to avoid hard coding passwords into an application that kicks off the pull replication on the client machine.
The client machines are all using SQL Server 2005 Express. The other machine is running SQL Server Standard. The passwords and login details are specified in the subscription properties in the Management Studio.
A fragment of the code is posted below. The transactional sychronization works fine without having to specify any passwords - however the merge replication does not work if both of the passwords are not specified.
private void SynchButton_Click(object sender, EventArgs e) { // Set up the subscriber connection details. subscriberConnection = new ServerConnection(subscriberName); try { // Connect to the Subscriber. subscriberConnection.Connect(); // Do the transactional subscription synchronisation independantly of the // merge subscription replication. try { transPullSubscription = new TransPullSubscription(subscriptionDbName, publisherName, publicationDbName, transPublicationName, subscriberConnection); // If the pull subscription and the job exists, start the agent job. if (transPullSubscription.LoadProperties() && transPullSubscription.AgentJobId != null) { TransSynchronizationAgent transSyncAgent = transPullSubscription.SynchronizationAgent; transSyncAgent.Synchronize(); } else { } } catch (Exception ex) { } // Do the merge subscription synchronisation independantly of the // transactional subscription replication. try { // Set up the subscription details for the merge subscription (bi-directional data) mergePullSubscription = new MergePullSubscription(subscriptionDbName, publisherName, publicationDbName, mergePublicationName, subscriberConnection); // If the pull subscription and the job exists, start the agent job. if (mergePullSubscription.LoadProperties() && mergePullSubscription.AgentJobId != null) { MergeSynchronizationAgent mergeSyncAgent = mergePullSubscription.SynchronizationAgent; mergeSyncAgent.DistributorPassword = "<<password>>"; mergeSyncAgent.PublisherPassword = "<<password>>"; mergeSyncAgent.Synchronize(); }etc etc..
Any help or suggestions will be greatly appeciated. Thanks.
View 8 Replies
View Related
Feb 6, 2008
Hi There,
Our company deals with financial education and typically has 9 different databases which have some cross referenced stored procedures. Every time we replicate Production database into TEST and DEV environments, we had to manually update the database references in Stored procedures. and it usually takes atleast a week and until then all the dev and test work has to wait.
Hence, I wanted to write a script, Here the code below.
-- These two variables must contain a valid database name.
DECLARE @vchSearch VarChar(15),
@vchReplacement VarChar(15)
SET @vchSearch = 'Search'
SET @vchReplacement = 'Replacement'
/*
-- Select the Kaplan Database Names in the Current Server
*/
DECLARE @tblDBNames TABLE (vchDBName VarChar(30))
INSERT INTO
@tblDBNames
SELECT
Name
FROM
MASTER.DBO.SYSDATABASES
WHERE
Has_DBAccess(Name)=1
And Name IN ( 'DB_DEV', 'DB_TEST', 'DB_PROD', 'WEBDB_DEV', 'WEBDB_TEST', 'WEBDB_PROD' , 'FINDB_DEV', 'FINDB_TEST', 'FINDB_PROD')
--SELECT * FROM @DBNames
IF @vchSearch NOT IN (SELECT vchDBName FROM @tblDBNames)
BEGIN
PRINT 'Not a Valid Search DB Name'
GOTO Terminate
END
IF @vchReplacement NOT IN (SELECT vchDBNAME FROM @tblDBNames)
BEGIN
PRINT 'Not a Valid Replacement DB Name'
GOTO Terminate
END
-- We have Valid DB Names, lets proceed...
--USE @vchReplacement
SET @vchSearch = '%' + @vchSearch + '..%'
SET @vchReplacement = '%' + @vchReplacement + '..%'
-- Get Names of Stored Procedures to be altered
DECLARE @tblSProcNames TABLE (vchSPName VarChar(100))
INSERT INTO
@tblSProcNames
SELECT
DISTINCT so.Name
FROM
SYSOBJECTS so
INNER JOIN SYSCOMMENTS sc
ON sc.Id = so.Id
WHERE
so.XType='P'
AND sc.Text LIKE @vchSearch
ORDER BY
so.name
-- Now, the table @tblSprocNames has the names of stored procedures to be updated.
-- And we have to Some HOW ?!! grab the stored proc definition and use REPLACE() to
-- update the database reference
-- Then, use cursors to loop through each stored proc and upate the reference
Now, I have got stuck how to extract the body of a stored procedure into a variable.
Please Help.... I dont want spend weeks of time in the future to do this work manually.
Madhu
View 24 Replies
View Related
Feb 9, 2012
I'm trying to insert data into a table from two tables into a single table along with a hard coded value.
insert into TABLE1
(THING,PERSONORGROUP,ACCESSRIGHTS)
VALUES
((select SYSTEM_ID from TABLE2 where
AUTHOR IN (select SYSTEM_ID from TABLE2 where USER_ID
=('USER1'))),(select SYSTEM_ID from TABLE2 where USER_ID
=('USER2')),255)
I get the following-
Msg 512, Level 16, State 1, Line 1
Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
The statement has been terminated.
Do I need to use a cursor?
View 5 Replies
View Related
Feb 3, 2007
I am new to scripting in general and I've run into an issue when attempting to write a VB variable to a database table in SQL Express. I am trying to record the value of the variable to the db, but it does not appear that the value is being passed to SQL. If I hard code the values in the SQL statement it works fine. Can someone explain what I'm doing wrong accomplish this? My code is below. Thanks in advance.
file.aspx
<asp:SqlDataSource ID="SqlDataSource" runat="server"
ConnectionString="<%$ ConnectionStrings:SqlConnectionString %>"
SelectCommand="SELECT * FROM [Table]"
InsertCommand="INSERT INTO [Table] (field1, field2) VALUES (& variable1 &, & variable2 &);" >
</asp:SqlDataSource>
file.aspx.vb
Protected Sub Button_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button.Click
Dim variable1 As String = FileUpload.FileName
Dim variable2 As String = Date.Now
Dim path As String = Server.MapPath("~/directory/)
If FileUpload.HasFile = True Then
Try
SqlDataSource.Insert()
FileUpload.PostedFile.SaveAs(path & _
FileUpload.FileName)
End Try
End If
End Sub
View 8 Replies
View Related
Oct 22, 2014
know a way to find all stored procedures that use declared or temp tables, i.e
Declare @temptable TABLE as....
Create table #temptable
View 8 Replies
View Related
Aug 4, 2006
Here is one such function:CREATE FUNCTION my_max_market_date () RETURNS datetimeBEGINDECLARE @mmmd AS datetime;SELECT max(h_market_date) INTO @mmmd FROM holdings_tmp;RETURN @mmmd;ENDOne change I had to make, relative to what I had working in MySQL, wasto insert 'AS' between my variable and its type. Without 'AS', MS SQLinsisted in telling me that datetime is not valid for a cursor; and Iam not using a cursor here. The purpose of this function is tosimplify a number of SQL statements that depend on obtaining the mostrecent datetime value in column h_market_date in the holdings_tmptable.The present problem is that MS SQL doesn't seem to want to allow me toplace that value in my variable '@mmmd'. I could do this easily inMySQL. Why is MS SQL giving me grief over something that should be sosimple. I have not yet found anything in the documentation for SELECTthat could explain what's wrong here. :-(Any ideas?ThanksTed
View 6 Replies
View Related
Apr 28, 2015
I am getting error [[Msg 16924, Level 16, State 1, Line 13
Cursorfetch: The number of variables declared in the INTO list must match that of selected columns.]] when i execute below script.
Declare @mSql1 Nvarchar(MAX)
declare @dropuser int
declare @dbname Nvarchar(max)
declare @username Nvarchar(max)
DECLARE Dropuser_Cursor CURSOR FOR
[Code] ....
View 9 Replies
View Related
May 1, 2008
is it possible to use twice declared. Variable names-
declared. Variable and after KILL
and use the same declared. Variable
like
DECLARE
@StartDate datetime
KILL @StartDate datetime (remove from memory)
use after with the same name
i have 2 big stored PROCEDURE
i need to put one after one
and psss only 1 Variable name to the second stored PROCEDURE
like this i don't get this error
The variable name '@Start_Date' has already been declared. Variable names must be unique within a query batch or stored procedure.
Msg 134, Level 15, State 1, Line 146
The variable name '@End_Date' has already been declared. Variable names must be unique within a query batch or stored procedure.
i use like
KILL @endDate ??
KILL @StartDate ??
TNX
View 12 Replies
View Related
Mar 29, 2008
I would like to have a stored procedure to run a shared VB file, which will check a refrence value from
a SQL Server table every hour, then redirect the web page to an error page if the reference value
is equal to e.g. 'E'.
My question is: a S.P. can update a SQL Server table, but can a S.P. 'run' a shared VB file to redicret
a web page automatically? How?
TIA,
Jeffrey
View 1 Replies
View Related
Nov 6, 2007
How do I dim SqlDbType in my code?Dim conn As New Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("TrainUserConnectionString").ConnectionString)
Dim cmd As New Data.SqlClient.SqlCommandWith cmd
.Connection = conn
.CommandType = Data.CommandType.StoredProcedure
.CommandText = "UpdateTopicscmd.Parameters.Add("@classificationID", SqlDBType.Int)cmd.Parameters.Add("@TitleID", SqlDBType.Int)
conn.Open()
For Each item As ListItem In CheckBoxList1.Items
If item.Selected Thencmd.Parameters("@classificationID").Value = item.Valuecmd.Parameters("@TitleID").Value = DropDownList1.SelectedValue
cmd.ExecuteNonQuery()
End If
Next
conn.Close()
End WithEnd Sub
End Class
View 1 Replies
View Related
Mar 26, 2008
I have simple SSIS package with only ScriptTask. Script was copied from MSDN:
Code Snippet
Imports System
Imports System.Data
Imports System.Math
Imports Microsoft.SqlServer.Dts.Runtime
Imports Microsoft.SqlServer.Dts.Tasks.ExecuteSQLTask
...
Public Sub Main()
Dim pkg As Package = New Package()
Dim exec1 As Executable = pkg.Executables.Add("STOCK:SQLTask")
Dim th As TaskHost
th = CType(exec1, TaskHost)
Dim myVar As Variable = pkg.Variables.Add("myVar", False, "User", 100)
th.Properties("SqlStatementSourceType").SetValue(th, SqlStatementSourceType.Variable)
...
Last line shows error - 'SqlStatementSourceType' is not declared.
Well, Microsoft.SqlServer.Dts.Tasks.ExecuteSQLTask is imported so SqlStatementSourceType should be visible. I don't see microsoft.sqlserver.sqltask.dll in task's references and can't add it because Add Reference doesn't show this DLL.
Could you please forward me in right direction?
Thank you,
Alexander
View 9 Replies
View Related
Feb 16, 2004
Hi,
I have a problem on setting the value for the variable in a declared cursor. Below is my example, I have declared the cursor c1 once at the top in a stored procedure and open it many times in a loop by setting the variable @str_var to different values. It seems the variable cannot be set after the cursor declared. Please advise how can I solve this issue.
------------------------------------------------------------------------
DECLARE @str_var VARCHAR(10)
DECLARE @field_val VARCHAR(10)
DECLARE c1 CURSOR LOCAL FOR
SELECT field1 FROM tableA WHERE field1 = @str_var
WHILE (Sometime TRUE)
BEGIN
....
SET @str_var = 'set to some values, eg. ABC123, XYZ123'
OPEN c1
FETCH c1 INTO @field_val
WHILE (@@fetch_status != -1)
BEGIN
PRINT @field_val
...
FETCH c1 INTO @field_val
END
CLOSE c1
END
DEALLOCATE c1
----------------------------------------------------------------------
Thanks a lots,
Vincent
View 4 Replies
View Related
Jul 20, 2005
I am trying to set up a "cmd.CommandType = adCmdStoredProc" but Ireceive the error "Type 'adCmdStoredProc' is not declared". What do Ineed to do to declare it? I am using MSDE with SQLDataAdapter. I amtrying to exceute a stored procedure from within my VB .NET 2003 code.Thanks.JH
View 5 Replies
View Related
Nov 17, 1999
When I execute next query on sqlserver 6.5 nested in stored procedure I can see that 'open testCursor' selected rows using new value of @var. When I execute query on sqlserver 7.0 I can see that 'open testCursor' selected rows using value of @var before 'declare ... cursor'. Is there any way to force sqlserver 7.0 to proccess cursor like it did it before.
select @var = oldValue
declare testCursor cursor
for select someColumns
from someTable
where someColumn = @var
select @var = newValue
open testCursor
fetch next from testCursor into @someColumns
Thank's in advance.
Mirko.
View 2 Replies
View Related
May 20, 1999
I need to be able to update a row of data in a table based upon the first character of a char(50) field.
if char(1) of employee_Job_class = "X" then update field Class_description = "Temporary"
Anyone have any suggestions ??
View 3 Replies
View Related
Mar 14, 2005
when I run this sproc all I get out of it is "the commands completed successfully" and doesn't return the value. If anyone can point out where the error is I would really appreciate it. Thanks
Code:
Create Procedure LookupLeagueIdByUserName(@userName as varchar(40) = '') as
begin
if (@userName = '')
raiserror('LookupLeagueIdByUserName: Missing parameters', 16,1)
else
begin
Declare @leagueId int
Set @leagueId = -1
--Check if the username belong to a player
Select @leagueId = leagueId From Users u
inner join players p on p.userId = u.userId
inner join teams t on p.teamId = t.teamId
where u.userName = @userName
if (@leagueId > 0)
begin
return @leagueId
end
else
begin
--Check if the username belong to a teamUser
Select @leagueId = leagueId From Users u
inner join teamUsers tu on tu.userId = u.userId
inner join teams t on tu.teamId = t.teamId
where u.userName = @userName
if (@leagueId > 0)
begin
return @leagueId
end
else
begin
--Check if the username belong to a leagueUser
Select @leagueId = leagueId From Users u
inner join leagueUsers lu on lu.userId = u.userId
where u.userName = @userName
if (@leagueId > 0)
begin
return @leagueId
end
else
begin
--username is not in db or is an admin user
return -1
end
end
end
end
end
return
-- when I run this I get no results returned
LookupLeagueIdByUserName 'chris'
View 2 Replies
View Related
Nov 15, 2007
I need to write a stored procedure using T-SQL to declare a cursor for containing id(staff_no), names and specialism of all doctors that have specialism, The contents of the cursor then are to be displayed using a loop and print statement to give a formatted display of the output of each record within the cursor.
The doctors table has the following columns with specialism allowing NULL values
doctor
(
staff_no CHAR(3),
doctor_name CHAR(12),
position CHAR(15),
specialism CHAR(15),
PRIMARY KEY(staff_no)
)
Any help would be greatly appreciated.
View 11 Replies
View Related
Mar 26, 2007
Doing a simple test with a script component in a DataFlow to transform some data from a flat file. I have new columns under the default Ouput 0 .. however in my code when I try this, I get the above error.
Public Overrides Sub Input0_ProcessInputRow(ByVal Row As Input0Buffer)
Output0Buffer.AddRow()
End Sub
There will of course be a lot more code in the Script Component, but not clear on why I can't reference it.
View 2 Replies
View Related
Jun 12, 2008
Morning All,Can I have some help with this one please, I am having to make a fixed length text file based on information from the DBDeclare @EDIString varchar(MAX)Declare @RecordType varchar(2)Declare @RegistrationMark varchar(7)Declare @Model_Chassis varchar(11)Declare @LocationCode Varchar(4)Declare @MovementDate varchar(8)Declare @IMSAccountCode varchar(5)Declare @MovementType varchar(8)Declare @NotUsed1 Varchar(28)Declare @NotUsed2 varchar(7)Select @RecordType = RecordType, @RegistrationMark = RegistrationMark, @Model_Chassis = Model_And_Chassis, @LocationCode = LocationCode, @MovementDate = MovementDate, @IMSAccountCode = IMSAccountCode, @Movementtype = MovementTypeCode from Fiat_OutBoundOnce I have selected the information from the DB I need to ensure that each field is the correct length. I therefore want to pass the variable and the length of the variable into a function to return the correct length.So if location Code = 'AB' this needs to be four characters long so want to pass it into a function and return 'AB 'As I need to do this for 70+ variables is there an easy way to obtain the length of the collation for the variable?regardsTom
View 1 Replies
View Related
Apr 19, 2008
I am trying to gather counts for table imports made for files from friday - sunday and create a variable that will be the body of an email.
I'd like to use either a case statement or a while statement since the query is the same but the values must be collected for each day (friday, saturday and sunday) and will all be included in the same email.
I have declared all variables appropriately but I will leave that section of the code out.
Select @ifiledate = iFileDate from tblTelemark where
iFileDate = CASE
WHEN iFileDate = REPLACE(CONVERT(VARCHAR(10), GETDATE()-3, 101), '/','') THEN
Select @countfri1 = Count(*) from tbl1
Select @countfri2 = Count(*) from tbl2
Select @countfri3 = Count(*) from tbl3
Select @countfri4 = Count(*) from tbl4
WHEN iFileDate = REPLACE(CONVERT(VARCHAR(10), GETDATE()-2, 101), '/','') THEN
Select @countsat1 = Count(*) from tbl1
Select @countsat2 = Count(*) from tbl2
Select @countsat3 = Count(*) from tbl3
Select @countsat4 = Count(*) from tbl4
WHEN iFileDate = REPLACE(CONVERT(VARCHAR(10), GETDATE()-1, 101), '/','') THEN
Select @countsun1 = Count(*) from tbl1
Select @countsun2 = Count(*) from tbl2
Select @countsun3 = Count(*) from tbl3
Select @countsun4 = Count(*) from tbl4
END
Is there a way to do what this that works???
View 3 Replies
View Related
Jan 15, 2007
Hi,I have a problem:I am writing an update script for a database and want to check for theversion and Goto the wright update script.So I read the version from a table and if it match I want to "GotoVersionxxx"Where Versionxxx: is set in the script with the right update script.Whenever I have some script which need Go commands I get error in theoutput thatA GOTO statement references the label 'Versionxxx' but the label hasnot been declared.But the label is set in the script by 'Versionxxx:'Is there a way I can solve this easily?Thanks in advance
View 5 Replies
View Related
Apr 8, 2007
Hi all..
I developed a local report to be viewed using the "Report Viewer" control. The report is attached to an object data source.
All works perfectly, now I want to display a declared value (from the form containing the report viewer) in a textbox. Like:
Dim NofDays as string
Me.ReportViewer1.LocalReport.textbox6.text = NofDays
I ve tried a lot of options like using the report paramaters but I cannot get it to work.
Does aneyone have a clue?
Thankzzzzzz
Juststar
View 5 Replies
View Related
Nov 16, 2007
I have declared a variable XYZ in Parent package
Similarly I have declared ABC in Child package and have done the configuration.
I have assigned some value to XYZ
How to get the value in Child Package.
View 6 Replies
View Related
Sep 16, 2015
I use BIDS 2008 R2 and I have a SQL script that works fine and gives me the desired output in SQL Management studio.
declare @dt datetime
select @dt = '2015-09-10 08:23:28.000'
select
   ref_id
   ,desn
   ,tran_date
   ,payment_due
   ,ref1
   ,gross_val
   from acptran (nolock) where seq_id in (select seq_id from acptcash (nolock) where date_time = @dt)
order by ref_id,ref1
However i need to create a report so that someone else can enter the date time as a parameter in a report to get the required results. Normally i would drop my SQL script into BIDS and it would create the dataset but as this has a declared value it gives an error "The Declare SQL construct or statement is not supported."
View 9 Replies
View Related
Mar 13, 2008
I have two tables - gift_cards and history - each related by a field called "card_number". This field is encrypted in the history table but not in the gift_cards table. Let's say the passphrase is 'mypassphrase'. The following query takes about 1 second to execute with a fairly large amount of data in both tables:
SELECT max([history].[date_of_wash]) AS LastUse
FROM gift_cards AS gc LEFT JOIN history
ON gc.card_number=CAST(DecryptByPassPhrase('mypassphrase', HISTORY.CARD_NUMBER) AS VARCHAR(50))
GROUP BY gc.card_number
When I use a declared variable to contain the passphrase, the same query takes over 40 seconds. For example,
declare @vchPassphrase as nvarchar(20)
select @vchPassphrase = 'mypassphrase'
SELECT max([history].[date_of_wash]) AS LastUse
FROM gift_cards AS gc LEFT JOIN history
ON gc.card_number=CAST(DecryptByPassPhrase(@vchPassphrase, HISTORY.CARD_NUMBER) AS VARCHAR(50))
GROUP BY gc.card_number
This query is part of a stored procedure and, for security reasons, I can't embed the passphrase in it. Can anyone explain the discrepancy between execution times and suggest a way to make the second query execute faster?
Thanks,
SJonesy
View 4 Replies
View Related