Can Varbinary And Varchar Lengths Be Declared Dynamically?

Mar 25, 2008

I just learned that bit masking a varbinary column can increase it's length in bytes unnecessarily. For example, I ran the following...

declare @v1 varbinary(max)

set @v1 = 0x0100AB

select len(@v1)

set @v1 = @v1 | (len(@v1) - 2) * 256

select master.dbo.fn_varbintohexstr(@v1)

select len(@v1)
...and get
3
0x00000000000101ab
8

This messes up a plan I had for varbinary column use.

So I quickly tried the following to look for strategies to deal with this unwanted growth...thought being that while I'm passed a varbinary(max), operating on a varbinary that matches its passed length would avoid the unwanted growth after bit masking....


declare @i int

set @i = 5

declare @v2 varbinary(@i)

...but got errors.

So I suppose I can use a combo of the len, substring etc functions to correct the situation after bit masking but would like to know if the more elegant approach of dynamically sizing a varbinary is possible in t-sql, or if perhaps there is a way to prevent the unwanted growth during bit masking.

View 6 Replies


ADVERTISEMENT

Converting Varbinary To Varchar

Jun 23, 2005

I have a password field which is of varbinary. Since its a varbinary I
cannot see the password in the database I only see hexadecimal values.
Now my question is that how can I convert those hexadecimal values to
string or varchar so I can read the password. 

any ideas ??

View 1 Replies View Related

How To Translate Varchar Into Varbinary?

Apr 3, 2007

Hi everyone,



We're trying to migrate a varchar field from Sql2k to varbinary in a sql25k through a dtsx package. We get an error which tell us: "data will be lost".



Does anyone have any idea about that?



Thanks for your time and inputs,

View 1 Replies View Related

VARCHAR(MAX), NVARCHAR(MAX) And VARBINARY(MAX) Support

Feb 12, 2007

On the ntext, text, and image (Transact-SQL) page at

http://msdn2.microsoft.com/en-us/library/ms187993.aspx

it states

"Important:
ntext, text, and image data types will be removed in a future version of Microsoft SQL Server. Avoid using these data types in new development work, and plan to modify applications that currently use them. Use nvarchar(max), varchar(max), and varbinary(max) instead. For more information, see Using Large-Value Data Types."

Considering this warning, is VARCHAR(MAX), NVARCHAR(MAX) and VARBINARY(MAX) support going to be implemented in SQL Server Compact Edition?

Robert Wishlaw

View 1 Replies View Related

How To Convert A Column Datatype From Varchar To Varbinary?

Feb 3, 2007

I have a password column that needs to be converted from varchar to varbinary. Can anybody provide me a proper CONVERT statement syntax for it?

View 12 Replies View Related

Retrieving Varchar(max) And Varbinary(max) Fields With VFP9

Mar 20, 2007

I have a test database that contains a varbinary(max) field and a varchar(max) field.

when I do a

Select * from test where id = xx

I get the expected results if my connection string uses

'driver=SQL Server;Server'

but these two fields return no data if I use

'driver=SQL Native Client'

the other fields in the record come back with no problems.

Is there anything special I need to do to retrieve these types of fields?

View 1 Replies View Related

Dynamically Changing The Length Of A Varchar(n) Field

Dec 26, 2006

Hi Everyone,I have a question about dynamically changing the length of a varchar(n)field, in case the value I'm trying to insert is too big and will givea "truncated" error, but before the error is given! i.e. Is there somekind of a way to "test" the length of the field while Inserting thevalue into it, and to have it automatically increase its length to thelength of the value being inserted, in case the value is too big?I've been able to do this in a "primitive" way, simply by identifyingthe specific error number in case the value is being truncated, andthen increasing the length of the varchar(n) field by using the ALTERcommand, and then duplicating the insert statement, but is there astandard (shorter) way of doing this?Here is my code (I'm working in an ASP environment):<%var_txt = "abcdefghijklmnopqrstuvwxyz12345678789"sql = "Insert Into Table1 (text) Values ('" & var_txt & "')"On Error Resume Nextconn.Execute sqlIf err = -2147217833 ThenResponse.Write "Error Recognized Successfully!<br /><br />"sql = "ALTER TABLE Table1 ALTER COLUMN text VARCHAR(" &Len(var_txt) &") NOT NULL"On Error Resume Nextconn.Execute sqlIf err<>0 ThenResponse.Write "Error while trying to alter Column:<br/>" & err & "= " & err.description & "<br />"ElseResponse.Write "Column altered successfully to: " &Len(var_txt) &"<br />"sql = "Insert Into Table1 (text) Values ('" & var_txt &"')"On Error Resume Nextconn.Execute sqlIf err<>0 ThenResponse.Write "<br />Error number 2:<br />" &err.description &"<br />"ElseResponse.Write "Now it was added successfully!HaHa!<br />"End IfEnd IfElseResponse.Write "Success."End If%>Thanks in advance!

View 2 Replies View Related

Is It Possible To Use Twice Declared. Variable Names- KILL And After Declared. Variable

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

Comparing Dates Of Different Lengths

Apr 9, 2008

Hi All,

Is there a way to compare two dates fields that are different in length? For example, I have table1.datefield with a date of '040808' and table2.datefield with a date of '04082008'. Just comparing the two fields is not coming up equal. Has anyone had this situation before?

Thanks.
Frank

View 1 Replies View Related

Zip Codes In Lengths Of 9,8,5 And4

May 2, 2007

I am working with a table that has zip codes listed in lengths of 9,8,5 and 4 digits. The table is created this way and I have no way of changing the data outside of SQL. I am trying to get the last four digits off of all the zip codes so that I only have to work with zip codes in lengths of 5 and 4

Thanks,

Pizzo36

View 5 Replies View Related

Programming Field Lengths

Jul 23, 2005

Is it possible to tell sql server to cast to a datatype and set thefield length to a variable.e.g. :-declare @flen intset @flen = 10select (cast somefield as char(@flen) newfield)into newtablefrom sometableI have also tried :-select (cast somefield as char(max(len(somefield))) newfield)into newtablefrom sometableWhen I try the above examples I get error in @flen; error in maxrespectivly.TIASimon

View 8 Replies View Related

Format Column Lengths

Sep 25, 2007

In Oracle sqlplus I always had a login.sql with statements like
column bldg_id format a8

which I could also use interactively on the sqlplus command line.

How can I do this in transact-sql ??

View 5 Replies View Related

JOINing On CHAR Fields Of Different Field Lengths

Nov 30, 2007

Can someone comment on why joining two tables on CHAR fields of different lengths would generate unexpected results?

I had an issue where I ran an update that used an inner join on two tables. The field I used in the join was char(50) in one table and char(13) in another table. The result gave bad matches. After changing the field types both to varchar(30), the problem was eliminate.

Any comments on this would be appreciated.



Rye Guy

View 3 Replies View Related

Cleartext - &&> Cipher Text. Field Lengths?

Aug 17, 2006

Suppose I store cleartext strings in a field declared as varchar(100). Is there any way to know the minimum varbinary column sze to use for the encrypted data? (e.g. should it be varbinary(100) or (200)?, (8000)?). I'm sure it's algorithm specific but I don't know what factors influence the final length.



TIA,

Barkingdog

View 1 Replies View Related

Audit Transformation Uses CURRENT Lengths For User Name And Machine Name Columns

Dec 2, 2007

I'll try to reproduce this later, but want to report it before I forget.

I just had my package fail on a VM I was testing on. It failed because on that machine, I logged in as MachineNameAdministrator instead of using my domain account (the VM is not in the domain).

This was a problem because the "User Name" column generated by the Audit Transformation was 17 characters long! This is the length of my domain + user name on my development machine. Similarly, the machine name length was 15 characters.

I'd love to know what the "correct" sizes are for these columns. In the meantime, I'm going to set these to 255 manually, and hope the size sticks.




P.S. There was one other post on this topic, though the thread isn't clear that this was the problem: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=472445&SiteID=1.

View 1 Replies View Related

Getting SqlDbType Not Declared

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

SqlStatementSourceType Is Not Declared

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

Set Value For Variable In A Declared Cursor

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

Type 'adCmdStoredProc' Is Not Declared

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

Using Declared Variables In SQL INSERT Statement.

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

Cursor Declared With Variable In Where Clause

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

Substringing Declared Varables In SQL Server

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

Problem Returning A Declared Variable

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

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 View Related

Stored Procedure Using A Declared Cursor

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

Script Component Name Ouput0Buffer Is Not Declared???

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

Obtaining Collation Length Of Declared Variable Within SP

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

Select Declared Variable With Case Statements

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

Go And Goto In One Sql Script Gives Error Label Not Declared

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

How Do I Asign A Textbox In A Rdlc Report A Declared Value?

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

How To Call A Variable Declared In Parent Package

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

Reporting Services :: Create A Report With Declared Value

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

Using Declared Variable As Passphrase Slows Query

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







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