I’m new to T-sql and need help understanding the CHAR() and ASCII functions.
I tried to run these commands to better understand them but I get the same results each time.
Here is the query with the char command
USE Northwind
SELECT FirstName + ' ' + LastName, + CHAR(13) + Address,
+ CHAR(13) + City, + Region
FROM Employees
WHERE EmployeeID = 1
Nancy Davolio
507 - 20th Ave. E.
Apt. 2A
Seattle WA
(1 row(s) affected)
Here is the same command without the char function.
USE Northwind
SELECT FirstName + ' ' + LastName, + address, + city, + region
from employees
where employeeID = 1
address city region
------------------------------- ------------------------------------------------------------ --------------- ---------------
Nancy Davolio 507 - 20th Ave. E.
Apt. 2A Seattle WA
(1 row(s) affected)
As you can see I get the same results back except for the column names being displayed.
( @CompanyID NVARCHAR(36), @DivisionID NVARCHAR(36), @DepartmentID NVARCHAR(36), @ItemID NVARCHAR(36), @OrderNo NVARCHAR(36), @LineNo NVARCHAR(36), @TAllotedQty Numeric, @EmployeeID NVARCHAR(36), @Trndate datetime ) AS BEGIN By default iam passing 12 char itemid as parameter...
Here iam selecting the itemid from InventoryLedger -if it is 8 char than this query should be executed IF EXISTS(SELECT ItemID FROM InventoryLedger WHERE TransDate=@Trndate AND ItemID=@ItemID AND ILLineNumber =@LineNo AND TransNumber=@OrderNo AND TransactionType='Production' AND CompanyID=@CompanyID AND DivisionID= @DivisionID AND DepartmentID=@DepartmentID)
BEGIN DECLARE @Qty INT
select @Qty =QUANTITY from inventoryledger WHERE TransDate=@Trndate AND ItemID=@ItemID AND ILLineNumber =@LineNo AND TransNumber=@OrderNo AND TransactionType='Production' AND CompanyID=@CompanyID AND DivisionID= @DivisionID AND DepartmentID=@DepartmentID select qtyonhand=qtyonhand+@Qty from InventoryByWareHouse where ItemID=@ItemID END
Here iam selecting the itemid from InventoryLedger -if it is 12 char than this query should be executed(both queries are same) IF EXISTS(SELECT ItemID FROM InventoryLedger WHERE TransDate=@Trndate AND ItemID=@ItemID AND ILLineNumber =@LineNo AND TransNumber=@OrderNo AND TransactionType='Production' AND CompanyID=@CompanyID AND DivisionID= @DivisionID AND DepartmentID=@DepartmentID)
BEGIN DECLARE @Qty INT
select @Qty =QUANTITY from inventoryledger WHERE TransDate=@Trndate AND ItemID=@ItemID AND ILLineNumber =@LineNo AND TransNumber=@OrderNo AND TransactionType='Production' AND CompanyID=@CompanyID AND DivisionID= @DivisionID AND DepartmentID=@DepartmentID select qtyonhand=qtyonhand+@Qty from InventoryByWareHouse where ItemID=@ItemID END
I was playing around with the new SQL 2005 CLR functionality andremembered this discussion that I had with Erland Sommarskog concerningperformance of scalar UDFs some time ago (See "Calling sp_oa* infunction" in this newsgroup). In that discussion, Erland made thefollowing comment about UDFs in SQL 2005:[color=blue][color=green]>>The good news is that in SQL 2005, Microsoft has addressed several of[/color][/color]these issues, and the cost of a UDF is not as severe there. In fact fora complex expression, a UDF in written a CLR language may be fasterthanthe corresponding expression using built-in T-SQL functions.<<I thought the I would put this to the test using some of the same SQLas before, but adding a simple scalar CLR UDF into the mix. The testinvolved querying a simple table with about 300,000 rows. Thescenarios are as follows:(A) Use a simple CASE function to calculate a column(B) Use a simple CASE function to calculate a column and as a criterionin the WHERE clause(C) Use a scalar UDF to calculate a column(D) Use a scalar UDF to calculate a column and as a criterion in theWHERE clause(E) Use a scalar CLR UDF to calculate a column(F) Use a scalar CLR UDF to calculate a column and as a criterion inthe WHERE clauseA sample of the results is as follows (time in milliseconds):(295310 row(s) affected)A: 1563(150003 row(s) affected)B: 906(295310 row(s) affected)C: 2703(150003 row(s) affected)D: 2533(295310 row(s) affected)E: 2060(150003 row(s) affected)F: 2190The scalar CLR UDF function was significantly faster than the classicscalar UDF, even for this very simple function. Perhaps a more complexfunction would have shown even a greater difference. Based on this, Imust conclude that Erland was right. Of course, it's still faster tostick with basic built-in functions like CASE.In another test, I decided to run some queries to compare built-inaggregates vs. a couple of simple CLR aggregates as follows:(G) Calculate averages by group using the built-in AVG aggregate(H) Calculate averages by group using a CLR aggregate that similatesthe built-in AVG aggregate(I) Calculate a "trimmed" average by group (average excluding highestand lowest values) using built-in aggregates(J) Calculate a "trimmed" average by group using a CLR aggregatespecially designed for this purposeA sample of the results is as follows (time in milliseconds):(59 row(s) affected)G: 313(59 row(s) affected)H: 890(59 row(s) affected)I: 216(59 row(s) affected)J: 846It seems that the CLR aggregates came with a significant performancepenalty over the built-in aggregates. Perhaps they would pay off if Iwere attempting a very complex type of aggregation. However, at thispoint I'm going to shy away from using these unless I can't find a wayto do the calculation with standard SQL.In a way, I'm happy that basic SQL still seems to be the fastest way toget things done. With the addition of the new CLR functionality, Isuspect that MS may be giving us developers enough rope to comfortablyhang ourselves if we're not careful.Bill E.Hollywood, FL------------------------------------------------------------------------- table TestAssignment, about 300,000 rowsCREATE TABLE [dbo].[TestAssignment]([TestAssignmentID] [int] NOT NULL,[ProductID] [int] NULL,[PercentPassed] [int] NULL,CONSTRAINT [PK_TestAssignment] PRIMARY KEY CLUSTERED([TestAssignmentID] ASC)--Scalar UDF in SQLCREATE FUNCTION [dbo].[fnIsEven](@intValue int)RETURNS bitASBEGINDeclare @bitReturnValue bitIf @intValue % 2 = 0Set @bitReturnValue=1ElseSet @bitReturnValue=0RETURN @bitReturnValueEND--Scalar CLR UDF/*using System;using System.Data;using System.Data.SqlClient;using System.Data.SqlTypes;using Microsoft.SqlServer.Server;public partial class UserDefinedFunctions{[Microsoft.SqlServer.Server.SqlFunction(IsDetermini stic=true,IsPrecise=true)]public static SqlBoolean IsEven(SqlInt32 value){if(value % 2 == 0){return true;}else{return false;}}};*/--Test #1--Scenario A - Query with calculated column--SELECT TestAssignmentID,CASE WHEN TestAssignmentID % 2=0 THEN 1 ELSE 0 END ASCalcColumnFROM TestAssignment--Scenario B - Query with calculated column as criterion--SELECT TestAssignmentID,CASE WHEN TestAssignmentID % 2=0 THEN 1 ELSE 0 END ASCalcColumnFROM TestAssignmentWHERE CASE WHEN TestAssignmentID % 2=0 THEN 1 ELSE 0 END=1--Scenario C - Query using scalar UDF--SELECT TestAssignmentID,dbo.fnIsEven(TestAssignmentID) AS CalcColumnFROM TestAssignment--Scenario D - Query using scalar UDF as crierion--SELECT TestAssignmentID,dbo.fnIsEven(TestAssignmentID) AS CalcColumnFROM TestAssignmentWHERE dbo.fnIsEven(TestAssignmentID)=1--Scenario E - Query using CLR scalar UDF--SELECT TestAssignmentID,dbo.fnIsEven_CLR(TestAssignmentID) AS CalcColumnFROM TestAssignment--Scenario F - Query using CLR scalar UDF as crierion--SELECT TestAssignmentID,dbo.fnIsEven_CLR(TestAssignmentID) AS CalcColumnFROM TestAssignmentWHERE dbo.fnIsEven(TestAssignmentID)=1--CLR Aggregate functions/*using System;using System.Data;using System.Data.SqlClient;using System.Data.SqlTypes;using Microsoft.SqlServer.Server;[Serializable][Microsoft.SqlServer.Server.SqlUserDefinedAggregate (Format.Native)]public struct Avg{public void Init(){this.numValues = 0;this.totalValue = 0;}public void Accumulate(SqlDouble Value){if (!Value.IsNull){this.numValues++;this.totalValue += Value;}}public void Merge(Avg Group){if (Group.numValues > 0){this.numValues += Group.numValues;this.totalValue += Group.totalValue;}}public SqlDouble Terminate(){if (numValues == 0){return SqlDouble.Null;}else{return (this.totalValue / this.numValues);}}// private accumulatorsprivate int numValues;private SqlDouble totalValue;}[Serializable][Microsoft.SqlServer.Server.SqlUserDefinedAggregate (Format.Native)]public struct TrimmedAvg{public void Init(){this.numValues = 0;this.totalValue = 0;this.minValue = SqlDouble.MaxValue;this.maxValue = SqlDouble.MinValue;}public void Accumulate(SqlDouble Value){if (!Value.IsNull){this.numValues++;this.totalValue += Value;if (Value < this.minValue)this.minValue = Value;if (Value > this.maxValue)this.maxValue = Value;}}public void Merge(TrimmedAvg Group){if (Group.numValues > 0){this.numValues += Group.numValues;this.totalValue += Group.totalValue;if (Group.minValue < this.minValue)this.minValue = Group.minValue;if (Group.maxValue > this.maxValue)this.maxValue = Group.maxValue;}}public SqlDouble Terminate(){if (this.numValues < 3)return SqlDouble.Null;else{this.numValues -= 2;this.totalValue -= this.minValue;this.totalValue -= this.maxValue;return (this.totalValue / this.numValues);}}// private accumulatorsprivate int numValues;private SqlDouble totalValue;private SqlDouble minValue;private SqlDouble maxValue;}*/--Test #2--Scenario G - Average Query using built-in aggregate--SELECT ProductID, Avg(Cast(PercentPassed AS float))FROM TestAssignmentGROUP BY ProductIDORDER BY ProductID--Scenario H - Average Query using CLR aggregate--SELECT ProductID, dbo.Avg_CLR(Cast(PercentPassed AS float)) AS AverageFROM TestAssignmentGROUP BY ProductIDORDER BY ProductID--Scenario I - Trimmed Average Query using built in aggregates/setoperations--SELECT A.ProductID,CaseWhen B.CountValues<3 Then NullElse Cast(A.Total-B.MaxValue-B.MinValue ASfloat)/Cast(B.CountValues-2 As float)End AS AverageFROM(SELECT ProductID, Sum(PercentPassed) AS TotalFROM TestAssignmentGROUP BY ProductID) ALEFT JOIN(SELECT ProductID,Max(PercentPassed) AS MaxValue,Min(PercentPassed) AS MinValue,Count(*) AS CountValuesFROM TestAssignmentWHERE PercentPassed Is Not NullGROUP BY ProductID) BON A.ProductID=B.ProductIDORDER BY A.ProductID--Scenario J - Trimmed Average Query using CLR aggregate--SELECT ProductID, dbo.TrimmedAvg_CLR(Cast(PercentPassed AS real)) ASAverageFROM TestAssignmentGROUP BY ProductIDORDER BY ProductID
I add some records to two tables after createing operation completed.
Then i use dbcc page command to oversee the structures of data page in two tables. I found some interest things: The rows in two tabes take up same space:9 bytes
You can see the "9" on top of the data, for example:Slot 0, Offset 0x60, Length 9, DumpStyle BYTE or calculate from the offset array
All, I have to automatically grap a dbf or ascii file from my hard drive and then insert that into an already existing database table. Does anyone know how to do this? The only thing I can find is to do it manually from enterprise manager, but I need to automate this.Thanks in advance!
I've got one SQL Server 7.0 table with a "Decsciption" Column of length 4000. The values in this column contains "End of Line" ASCII Character. The ASCII Value of this character is 10. I'm not able to remove this ASCII Character. I tried by using REPLACE function. But i could not remove that character.
I have an file I FTP onto the server using a FTP task in my DTS package. The problem I'm having is the FTP task downloads using binary format, whereas I need it to download using ascii format. Binary is causing characters in the file to change, and my import is failing.
Hi I am importing data from mainframe using DTS the problem is that I am getting some COMP fields from the mainframe these are compressed data fields that are used to reduce storage space on the main frame. Can some one please help me understand how we can use DTS to solve this problem that is decompress it before transferring to table in SQL server. any code in scripting language to help decompress this datatype will be really appreciated.
Dear all, I've a different problem while writing some script.
actually i need all the currency symbols and its ascii values. i downloaded from one website, it is showing correctly in msword. but i'm not getting the same thind in EDITPLUS.
Dear all, I've a different problem while writing some script.
actually i need all the currency symbols and its ascii values. i downloaded from one website, it is showing correctly in msword. but i'm not getting the same thing in EDITPLUS.
item custclass totalcustclass ------------------------- 06-5841 INST-CLINPRAC 1 06-5841 INST-MKT/MEDIA 2 06-5841 PROGRAM 1 06-5841 STANDARD 4 06-5845 STANDARD 1 AX-048 INST-MKT/MEDIA 4 KT-048 PROGRAM 2 KT-048 STANDARD 4
i want condition like if item is starting with number then totalcustclass whcih is count(*) remain same giving correct results...but if item startign with ascii character then totalcustclass r getting double so i have to /2..
i want results:
item custclass totalcustclass ------------------------- 06-5841 INST-CLINPRAC 1 06-5841 INST-MKT/MEDIA 2 06-5841 PROGRAM 1 06-5841 STANDARD 4 06-5845 STANDARD 1 AX-048 INST-MKT/MEDIA 2 KT-048 PROGRAM 1 KT-048 STANDARD 2
select item, custclass,
case when item is <ascii> then count(custclass)/2 else count(custclass) as totalcustclass
from itemcustclass
can anyone tell me what condition will come in case?
I have data that comes from a legacy system. I can obtain the data in anASCII format. Currently I have created scripts in ACCESS to import the datainto tables.What I would like to do is create an automated import function in SQL.I am new to SQL, can anyone point me in the direction I should look to findout how I could perform this task?Using SQL 2005.ThanksMatt--Matt Campbellmattc (at) saunatec [dot] comMessage posted via http://www.sqlmonster.com
I need to generate Ascii 7 bit flat file, based on data in db, using integration services, FTP task. Currently i am generating file with ansi-latin and then using the script task converting it to the ascii 7. File looks to be generated properly. But when the target system reads this, they complain that the file has junk charecters some thing like this. when i open it after generating the file it looks fine to me in DOS also. I dont know what is the target system and what OS is used by them. what cud be the issue for these junk charecters and is it possible that a Ascii 7 file generated by windows doesnt work in other OS? If the method i am doing to generate the ascii 7 is not currect then what is the best method for this?
PS: earlier i had generated a flat file using data export from Excel & that worked in the target system well. is there any difference in the file encoding generated by excel and integration services?
I am working on a project that will be mimicking an existing interface that we have with one our our clients. That interface today sends EBCDIC packed fields. We do not want to introduce changes to the external clients interface file when we rebuild it in SQL 2005 Integration Services and I need to find out how I can take ASCII data and convert it to the host (mainframe) representation, which is what we currently provide to our external client using Integration Services.
Has anyone had to do this? If so, can I accomplish it natively with SSIS, or do I need to look to a third party vendor for a component?
I am glad if someone help me. My question is like belo:
i have ascii data in one column name(failcode), i want to use it to link with other table which is the data type in integer. so i have to convert it into integer type.
May i know how to write in query to convert ascii to int in Sequence Server(Microsoft SQL Server 7.0)?
I have a problem with alot of my SPs. All compile correctly but cause erroneous data due to IF statements begin ignored due to
characters (see below).
Example SP... -- Opened within last 12 Months
IF @NEWACCIND = 1 BEGIN
EXECUTE usp_DFDX03_D0150_A4 @COSTALL OUTPUT END
-- Accounts in Arrears in Current Quarter
Should look like ...
-- Opened within last 12 Months IF @NEWACCIND = 1 BEGIN
EXECUTE usp_DFDX03_D0150_A4 @COSTALL OUTPUT END -- Accounts in Arrears in Current Quarter
I need to find all SPs with double
instance and manually replace. There are hundreds of SPs in total. I have tried
SELECTCOLID, ID FROMSYSCOMMENTS WHERECHARINDEX (CONVERT (VARCHAR(3), CHAR(13)+CHAR(13)), TEXT) > 0
but this also returns SPs containing 2 consecutive blank lines as well (which there are alot of due to formatting of T-SQL). Really I need to distuinguish between and new line which both appear to be CHAR(13)
Thought I would share this since it caused me so much grief.
In some mainframe systems, some dates are stored as the string "00000000". In my SSIS package, I was trying to anticipate for this string, as well as any other combination of zeros (e.g., "000", "0000", etc), since I had already seen lots of dirty data in the flat file (like non-printing characters, etc).
So, what I tried to do was perform an integer conversion on the string and test if it was the equivalent of the numerical value zero:
Code Snippet
(DT_STR)[ColumnName] == 0 ? .... Now, for some reason, that doesn't work, even though a similar operation in SQL does work:
Code Snippet
SELECT TOP 1 ISNUMERIC('00000000') FROM tableName
In the end, I had to resort to testing for a match on the literal string "00000000" and hope that no other dates came in as "000" or other variation. Fortunately, this has been true so far.
However, the moral of the story is, converting a series of zeros into a numeric zero, and testing against that, does not seem to work. I don't have a good explanation for why that is, but I would guess it has something to do with the limitation of the conversion function.
I tried to setup a flat file data source that has code page 37 (EBCDIC)
Then I have a flat file destionation that is ASCII.
And inbetween I have tried several different data flow conversion tasks liked Data Conversion, and Derived Column. But I keep getting errors about different code pages.
I also tried to load the EBCDIC data into a SQL Server DB, and it complains about different code page.
Has anyone been able to do this with SSIS out of the box, without any extra components ?
I've an issue with double-quotes in CSV file. One of the columns may contain this kind of value: "STATUS ""H"" "
I've got quote set to "
The file source fails on such records.
I found this thread and Scott tells us there that the file can't contain " in data.
Is this 100% correct?
I've got mutliple text columns and the pain is that I don't know which column might have these cases in future. To create a script means to write my own file parser for all files I use.
I'm working on a database conversion from Sybase to SQL Server 2005 and have hit a wall with a character conversion problem when reading non-ASCII characters (encrypted password string) via JDBC.
My application runs on Solaris and accesses a SQL Server 2005 database via the Microsoft JDBC driver. The server was unfortunately specified as having a SQL_Latin1_General_CP1_CI_AS collation at installation time, and the database being accessed has taken this default. After creation the data was migrated across via DTS.
The invalid character is a dagger '†'. When read over JDBC it is converted to a question mark '?'.
In my original environment a Sybase database was accessed via JDBC driver from Solaris and the correct value was returned. The Sybase database used Latin1_General_BIN as it's collation. By way of experimentation I have modified the default collation sequence within the SQL Server 2005 database, and created a new table to hold the password. I am then able to correctly return strings containing this character from within SQL Server Management Studio, but the same problem still exists when accessing it via JDBC.
I am not sure where to focus my investigation and would be grateful for any useful pointers/advice. To me it looks like it's a JDBC driver issue as with the change in collation it works from a non-JDBC client.
Adedoyin Akinnurun writes "i have a database that is running using regular ascii characters.. i am trying to migrate this database to support several other languges(globalization). I need ideas on how to migrate this database to UTF 8 . Someone suggested converting all the varchar and char to nvarchar and nchar .. but i have a lot of data on the system and this might take a lot of time.. Any ideas would be appreciated !!!!"
Our database defines the long_value column as nvarchar(max). I want to find out which rows actually contain non-ASCII characters in that column, but this clause also returns rows with only ASCII characters:where long_value like (N'%[' + nchar(128) + N'-' + nchar(65535) + N']%')
im new to the ASP/SQL scene, so please bare with me.
i have to send an email (with two attachments) through sql server.
the mail arrives, but the attachments are not attachments... they are ascii text in the body. im using an existing stored proc, which apparently works. so there is no reason this shouldn't work.
The file exists, the path is correct. Its obviously seeing and reading the file (otherwise there would be no data to print as ascii)
thanks all.
Also, if you know of a better place where i can post this thread, please let me know
I have to write a program in VB to receive the read data from a RFID reader for my graduation project.The problem is I am not a computer science student so I have only general info on programming.
I created my DB in VB express but I couldn't find out how to send the read data (that will be either in XML or ASCII format) to my database...The read data will be transferred to my computer by the RFID reader's software but after that I don'T know how to transfer it to my DB.As I know I have to use commands like read.xml etc,but no idea how write the complete program.
I checked the forum and couldn't find the answer,sorry if someone already answered my question and I missed it.
Hi, i've question about how to import an ascii-file in a sql 2005 table. I want to import this file also with an unique key. There i first have to get the last key form the table and then raise this key. Next step is to use this key during the import.
How do i have to do this in ssis? Thanks in advance
I want to insert things to SQL-server from an ascii file but I also want to add logics with IF - Then _ Else statements. I guess the only way is to make a stored Procedure.
How do you do when you want to read from a text file using the data into variables and then write it into the database ?
SQL SERVER 2000: My problem is that I have to process a special text file every day which contains 0 ASCII values to separate fields. The DTS import program drops everything after the ascii 0 value in the row, but of course I need the entire row with all fields. So how can I prevent the text file import task from dropping everything after the 0 ascii value?