I am using crystal reports for reporting. I have a small problem, actually I have a field call {id} on my report that is bound to an identity of my sql table. It shows values like 1,2,3,4 but I want my values to be padded with zeros on left to make it 7 digits in all. Ex- 0000001,0000002,0000003,0000004, and for 1234 it should be 0001234.
I tried Right("0000"&{MyFieldToPad},7) but its not working, it says it need boolean!
In your SQL query instead of saying
SELECT id
--, other columns
FROM dbo.table
WHERE ...
;
Say:
SELECT RIGHT('0000000' + CONVERT(VARCHAR(12), id), 7)
--, other columns
FROM dbo.table
WHERE ...
;
If {table.id} is numeric, you need to use the totext() function to specify the format and convert it to a string: totext({table.id},"0000000")
If {table.id} is a varchar, then your sample formula should work: right("0000000"&{table.id},7) No idea why it would say you need a boolean... My guess is that you're not creating a new formula like you should be and instead putting that code where it doesn't belong. Try creating a new formula from scratch with just that code.
Related
I want to save a car plaque in the order below.
Example:
12 Persian character 423
First, two digits, then a Persian character followed by three digits.
But this is stored in SQL Server:
Data type for plaque:
What needs to be done in order I want to save and then read it?
Looking to save Unicode? Use the N prefix:
INSERT INTO YourTable(yourcolumn)
VALUES (N'yourstring')
Update: Trickery to store the value without getting reversed:
Create Table #tbl
(
val nVarChar(25)
)
insert into #tbl select Reverse((Reverse(N'12')+N'ص' + Reverse(N'423')))
Select * From #tbl
Values with prefix 'N' to solve your problem.
I'm having a question regarding replacing characters on a specific location in a string. My c# application has the ability to read files such as: TXT, CSV, Excel, database, etc. and import them to a SQL server on the network (the user is able to choose to which server we import the files). The application is ment to compare the two imported files with eachother. To improve the comparison between the two tables I want to be able to replace some specific characters. To give you an example. One column in the first imported file has part numbers without any special characters. The second imported file also have a column with the same part numbers as the first imported file does, only those partnumbers are seperated with a dot on every third character. To improve the search I remove ALL the dots from the second imported file. This can easily be done with a REPLACE transact. The query (that is exectuded from my c# application, I don't want to make a stored procedure because the server can be changed by the user's choice) will look like this:
UPDATE myTable SET myColumn = REPLACE(myColumn , '.', '');
This replace statement is working just fine. However the hard part I want to achieve. Lets say a column in the first imported file has partnumbers that looks like this:
132105213.000
452993424.001
436345332.002
etc...
And the second imported file has the same partnumbers only they look like this:
132.105.213.000
452.993.424.001
436.345.332.002
etc...
To improve the comparison between those two column I only want to remove the FIRST TWO dots and leave the third dot. So the REPLACE transact should only be executed on character 4 to 8. Is there any way to do this on the server side?
Some things to consider:
I don't want to use the STUFF transaction, because every character string on a row could be different from eachother and mess up the replacing.
The user is specifying the range where the REPLACE transact should be executed on. E.g. the user is entering replace from character position 4 to position 8.
Preferably without making a stored procedure as the comparison server can differ by the user's choice.
Preferably from SQL Version 2005 and up. Absolute lowest version will be SQL Server 2008.
If more info needed place a comment below so I can edit my question!
I don't understandand your adversity to STUFF, the following seems like it would work fine:
DECLARE #Start INT = 4,
#End INT = 9,
#Replace NCHAR(1) = '.';
SELECT s = STUFF(t.String,
#Start,
#End - #Start,
REPLACE(SUBSTRING(t.String, #Start, #End - #Start), #Replace, '')
)
FROM (VALUES
('132.105.213.000'),
('452.993.424.001'),
('436.345.332.002'),
('132105213.000'),
('452993424.001'),
('436345332.002')
) AS t (String);
Basically you are extracting the string between the specified characters (SUBSTRING(t.String, #Start, #End - #Start)), then performing the replace on this extract, and stuffing what is left back into the original string.
Try this. It will leave the last period
DECLARE #t table(val varchar(50))
INSERT #t values
('132.105.213.000'),
('452.993.424.001'),
('436.345.332.002'),
('123')
SELECT replace(left(val, len(val) - len(rightval)), '.', '') + rightval
FROM #t t
OUTER APPLY
(SELECT right(val, charindex('.',reverse(val))) rightval) x
The answers you provided helped me with figuring out the solution, atleast I think it is a good solution? This is how the query looks like:
UPDATE myTable
SET myColumn = STUFF(myColumn, fromCharPosition, toCharPosition, REPLACE(SUBSTRING(myColumn, fromCharPosition, toCharPosition, charToReplace, charReplacement));
So the query will look like this for the example I made in my question:
UPDATE myTable
SET partNumber = STUFF(partNumber, 4, 8, REPLACE(SUBSTRING(partNumber, 4, 8), '.', ''));
Again thanks for helping out this trainee!
This question already has answers here:
SQL Identity with leading padded zeros
(7 answers)
Closed 9 years ago.
SQL Query For Create Table
CREATE TABLE Test
(ID int,
Value1 int,
Value2 int,
)
SQL Query For Insert Value
INSERT INTO Test
VALUES(001,200,300)
OutPut
ID Value1 Value2
1 200 300
Query To Display 00 In Result
SELECT RIGHT('00' + CAST([ID] AS varchar(5)) , 3),Value1,Value2
FROM Test
Now The Output Is
001 200 300
My Id Value Is maximum 5 Digit
Example 00001,00010,00100,01000,10000
Now i Want To Display The Result Like
00001,00010,00100,01000,10000
I Need A Query Automatically Find Out How Many Zero Present Before The Number
Example 00001 This Value Have 4zero , 00010 This Value Have 3 Zero.
How To Use This Query
SELECT RIGHT('00' + CAST([ID] AS varchar(5)) , 3),Value1,Value2
FROM Test
For Find Out How Many Zero Present And Display The Result With zero
Numeric data types don't contain leading zeros. If you need to store leading zeros, you need to use a character datatype.
If you do that, however, to store numbers without leading zeros, please note that sorting on a character datatype field is done lexicographically, so you might end up with something like this:
1
10
11
2
20
21
Also, you should note the difference between data storage and data display. You could well store numbers without leading zeros, but make your application display them containing leading zeros!
As other people have noted, something like
SELECT RIGHT('00' + CONVERT(NVARCHAR, Field), 3)
will help you select the content of a numeric field as a string with leading zeros.
You could also do that in C# using
String.Format("{0:d3}", fieldvalue);
You are basically saying "I want to store a non-integer value in an integer column, how do I do that?"
Now, the obvious answer is of course: you don't.
The real question is, why do you think you want this? If (as I suspect) it is for later display purposes, then forget about inserting invalid data and focus on the real issue: how do I display my data the way I want to?
And the answer to that is simply": anywhere but in your database :)
You can change your integer to a string before displaying, either in your select statement, or further on in your front end.
You'd have to format the number manually. One way to do that:
select right('00' + cast(ID as varchar(3)),3)
SELECT RIGHT('00' + CAST([ID] AS varchar(5)) , 3)
FROM test
The 3 is the number of characters you want total in the output display
First you can't insert the value 00002 or anything like that with zeros (only in int type)... so the concept is fully wrong... or else change your data type to varchar then you can do these things...
if you are using varchar then simply use the following function
reverse()
I am building a website in ASP.NET 2.0, some description of the page I am working about:
ListView displaying a table (of posts) from my access db, and a ListBox with Multiple select mode used to filter rows (by forum name, value=forumId).
I am converting the ListBox selected values into a List, then running the following query.
Parameter:
OleDbParameter("#Q",list.ToString());
Procedure:
SELECT * FROM sp_feedbacks WHERE forumId IN ([#Q])
The problem is, well, it doesn't work. Even when I run it from MSACCESS 2007 with the string 1,4, "1","4" or "1,4" I get zero results. The query works when only one forum is selected. (In (1) for instance).
SOLUTION?
So I guess I could use WHERE with many OR's but I would really like to avoid this option.
Another solution is to convert the DataTable into list then filter it using LINQ, which seems very messy option.
Thanks in advance,
BBLN.
I see 2 problems here:
1) list.ToString() doesn't do what you expect. Try this:
List<int> foo = new List<int>();
foo.Add(1);
foo.Add(4);
string x = foo.ToString();
The value of "x" will be "System.Collections.Generic.List`1[System.Int32]" not "1,4"
To create a comma separated list, use string.Join().
2) OleDbParameter does not understand arrays or lists. You have to do something else. Let me explain:
Suppose that you successfully use string.Join() to create the parameter. The resulting SQL will be:
SELECT * FROM sp_feedbacks WHERE forumId IN ('1,4')
The OLEDB provider knows that strings must have quotation marks around them. This is to protect you from SQL injection attacks. But you didn't want to pass a string: you wanted to pass either an array, or a literal unchanged value to go into the SQL.
You aren't the first to ask this question, but I'm afraid OLEDB doesn't have a great solution. If it were me, I would discard OLEDB entirely and use dynamic SQL. However, a Google search for "parameterized SQL array" resulted in some very good solutions here on Stack Overflow:
WHERE IN (array of IDs)
Passing an array of parameters to a stored procedure
Good Luck! Post which approach you go with!
When you have:
col in ('1,4')
This tests that col is equal to the string '1,4'. It is not testing for the values individually.
One way to solve this is using like:
where ','&#Q&',' like '*,'&col&',*'
The idea is to add delimiters to each string. So, a value of "1" becomes ",1,"in the column. A value of "1,4" for #Q becomes ",1,4,". Now when you do the comparison, there is no danger that "1" will match "10".
Note (for those who do not know). The wildcard for like is * rather than the SQL standard %. However, this might differ depending on how you are connecting, so use the appropriate wildcard.
Passing such a condition to a query has always been a problem. To a stored procedure it is worse because you can't even adjust the query to suit. 2 options currently:
use a table valued parameter and pass in multiple values that way (a bit of a nuisance to be honest)
write a "split" multi-value function as either a UDF or via SQL/CLR and call that from the query
For the record, "dapper" makes this easy for raw commands (not sprocs) via:
int[] ids = ...
var list = conn.Query<Foo>(
"select * from Foo where Id in #ids",
new { ids } ).ToList();
It figures out how to turn that into parameters etc for you.
Just in case anyone is looking for an SQL Server Solution:
CREATE FUNCTION [dbo].[SplitString]
(
#Input NVARCHAR(MAX),
#Character CHAR(1)
)
RETURNS #Output TABLE (
Item NVARCHAR(1000)
)
AS BEGIN
DECLARE #StartIndex INT, #EndIndex INT
SET #StartIndex = 1
IF SUBSTRING(#Input, LEN(#Input) - 1, LEN(#Input)) <> #Character
BEGIN
SET #Input = #Input + #Character
END
WHILE CHARINDEX(#Character, #Input) > 0
BEGIN
SET #EndIndex = CHARINDEX(#Character, #Input)
INSERT INTO #Output(Item)
SELECT SUBSTRING(#Input, #StartIndex, #EndIndex - 1)
SET #Input = SUBSTRING(#Input, #EndIndex + 1, LEN(#Input))
END
RETURN
END
Giving an array of strings, I will convert it to a comma separated List of strings using the following code
var result = string.Join(",", arr);
Then I could pass the parameter as follows
Command.Parameters.AddWithValue("#Parameter", result);
The In Stored Procedure Definition, I would use the parameter from above as follows
select * from [dbo].[WhateverTable] where [WhateverColumn] in (dbo.splitString(#Parameter, ','))
I am using SQL Server 2008, Visual Web Developer 2012 and .net 4.0. I created a table in SQL Server and added some columns to it. I gave some columns the datatype nchar(10).
Now my problem is that when I insert string of less than 10 characters as a value of the column type nchar(10) and when I fetched the value it inserts blank spaces to complete the 10 character string.
Means if I insert "a" into column of type nchar(10),
then when I fetch the value again I get back: "a "
How can I resolve this issue ?
You can do like this to trim the whitespaces:
SELECT RTRIM(CAST(col As NVARCHAR(10))) FROM test
Check out SQLFIDDLE
define the string as nvarchar(10) it will work fine
If you don't want to change data type, then you will need to TRIM the space from the output
SELECT
RTRIM("a ") AS ColumnName
FROM MyTable
But this means every time you have to do this every place you are using the column. It is better to user VARCHAR(10) or NVARCHAR(20) where VAR... means variable length. So if your string is not up to 10 characters, spaces are not added
Final SQL
SELECT
RTRIM(ColumnName) AS ColumnName
FROM myTable