Compare if textfield value is greater then x - sql

How can I compare a numeric value in a textfield against any given value x?
Iam writing the code in TSQL.
See code below:
DECLARE #TA_SM varchar(5000)
DECLARE #TA_MSD varchar(5000)
DECLARE #T_SUM int(5)
SET #TA_SM = '[field name='Toelichting_advies_ISM']'
SET #TA_MSD = '[field name='Toelichting_advies_MSD']'
SET #T_SUM = '[field name='Offerte_totaalsom']'
IF ((#TA_SM = '') OR (#TA_MSD = '')) AND (#T_SUM >25.000)
SELECT 1
ELSE
SELECT 2
I get a error message saying:
Must declare the table value #T_SUM
The statement before the AND operator is working just fine.

Change the DECLARE #T_SUM int(5) to DECLARE #T_SUM int.
If you only want to have 5 digits use NUMERIC instead of INT.
EDIT 1 - Full code.
This should run through in TSQL without error but I am not sure if this is the result you are looking for. I have added extra quote marks to your variables definitions.
BEGIN
DECLARE #TA_SM varchar(5000)
DECLARE #TA_MSD varchar(5000)
DECLARE #T_SUM int
SET #TA_SM = '[field name=''Toelichting_advies_ISM'']'
SET #TA_MSD = '[field name=''Toelichting_advies_MSD'']'
SET #T_SUM = '[field name=''Offerte_totaalsom'']'
IF ((#TA_SM = '') OR (#TA_MSD = '')) AND (#T_SUM >25.000)
SELECT 1
ELSE
SELECT 2
END

Related

SQL Server pass in string value and see if it is in a hard-coded list of values and return int

I have a stored procedure that I have created that for right now I am not touching a database.
Pseudo code
CREATE PROCEDURE [dbo].[CustomerKeyChecker]
#ldccode VARCHAR(12)
AS
#result int = 0
BEGIN
DECLARE #listofCodes varchar(200)
SET #listofCodes = 'CLP, UIC, NSTAR, NSTARB, NSTARC, PSNH'
-- So lets say that the passed in #ldccode is "CLP" , well then I went to
-- set a #result = 1
END
What is the a decent way to do a substring to search for these codes inside list?
Pseudo code:
substring(#lcdcode, #listOfCodes) ?
Again, for now this is nothing to do with the database, and I understand that someone would say "why even pass this data to sql" ... there will be sql tables added in later is why ...
You may notice that we add a space to the begining and comma to the end of each variable. This is to prevent false positives i.e. STAR. You may also notice SIGN(), this will return 1 if a positive number, 0 if not found.
Declare #ldccode VARCHAR(12) = 'CLP'
Declare #result int = 0
declare #listofCodes varchar(200)
SET #listofCodes = 'CLP, UIC, NSTAR, NSTARB, NSTARC, PSNH'
Select #result=sign(charindex(' '+#ldccode+',',' '+#listofCodes+','))
Returns
1

Find all ERDs containing table with specified name

Is it possible that I can query for names of all ERDs (Entity Relationship Diagram) which contain table with name
Like '%mytable%'
Something like this:
select *
from <ERD objects>
where tableName like '%%'
Actually, I have a large Database with lots of ERDs. So, to understand the scope of a table I want to browse ERDs of that specific table.
As I understand you need a list of tables contained in a database diagrams. There you can help this article. I will add part of it here:
The diagram itself is stored in a binary field. And you can not convert it into readable form without difficulties. For deserializing this field (called definition) we need 2 functions:
CREATE FUNCTION [dbo].[Tool_VarbinaryToVarchar_Text]
(
#VarbinaryValue VARBINARY(max),
#bitASCIIOnly BIT = 0
)
RETURNS VARCHAR(max) AS
BEGIN
DECLARE #NumberOfBytes INT
SET #NumberOfBytes = DATALENGTH(#VarbinaryValue)
-- PART ONE --
IF (#NumberOfBytes > 4)
BEGIN
DECLARE #FirstHalfNumberOfBytes INT
DECLARE #SecondHalfNumberOfBytes INT
SET #FirstHalfNumberOfBytes = #NumberOfBytes/2
SET #SecondHalfNumberOfBytes = #NumberOfBytes - #FirstHalfNumberOfBytes
-- Call this function recursively with the two parts of the input split in half
RETURN dbo.Tool_VarbinaryToVarchar_Text(CAST(SUBSTRING(#VarbinaryValue, 1 , #FirstHalfNumberOfBytes) AS VARBINARY(max)),#bitASCIIOnly)
+ dbo.Tool_VarbinaryToVarchar_Text(CAST(SUBSTRING(#VarbinaryValue, #FirstHalfNumberOfBytes+1 , #SecondHalfNumberOfBytes) AS VARBINARY(max)),#bitASCIIOnly)
END
IF (#NumberOfBytes = 0)
BEGIN
RETURN '' -- No bytes found, therefore no 'hex string' is returned
END
-- PART TWO --
DECLARE #HighByte INT
-- #NumberOfBytes <= 4 (four or less characters/8 hex digits were input)
-- eg. 88887777 66665555 44443333 22221111
-- We'll process ONLY the right-most (least-significant) Byte, which consists
-- of eight bits
-- 2. Carve off the rightmost eight bits/single hex digit (ie 22221111)
-- Divide by 16 does a shift-left (now processing 2222)
SET #HighByte = CAST(#VarbinaryValue AS INT) & 255
IF #bitASCIIOnly = 1 AND (#HighByte < 32 OR #HighByte > 126) SET #HighByte=13;
-- 3. Trim the byte (two hex values) from the right (least significant) input Binary
-- in preparation for further parsing
SET #VarbinaryValue = SUBSTRING(#VarbinaryValue, 1, (#NumberOfBytes-1))
-- 4. Recursively call this method on the remaining Binary data, concatenating the text
-- 'value' we just decoded as their ASCII character representation
-- ie. we pass 88887777 66665555 44443333 back to this function, adding X to the result string
RETURN dbo.Tool_VarbinaryToVarchar_Text(#VarbinaryValue,#bitASCIIOnly) +
CHAR(#HighByte)
END
And:
CREATE FUNCTION [dbo].[fnTool_ScriptDiagram2005_Text]()
RETURNS
#tblOut TABLE
(
-- Add the column definitions for the TABLE variable here
diagramname NVARCHAR(128),
diagram_id INT PRIMARY KEY,
diagram_text VARCHAR(MAX),
diagram_ASCII VARCHAR(MAX)
)
AS
BEGIN
DECLARE #name NVARCHAR(128);
DECLARE #diagram_id INT;
DECLARE #index INT;
DECLARE #size INT;
DECLARE #chunk INT;
DECLARE #line VARCHAR(MAX);
DECLARE #lineASC VARCHAR(MAX);
DECLARE #CurrentPos INT;
SELECT #CurrentPos = MIN(diagram_id) FROM dbo.sysdiagrams;
WHILE (#CurrentPos IS NOT NULL)
BEGIN
-- Set start index, and chunk 'constant' value
SET #index = 1; --
SET #chunk = 32; -- values that work: 2, 6
-- values that fail: 15,16, 64
SELECT #diagram_id = diagram_id,
#size = DATALENGTH(definition),
#name = name
FROM dbo.sysdiagrams
WHERE diagram_id = #CurrentPos;
-- Now with the diagram_id, do all the work
SET #line = '';
SET #lineASC = '';
WHILE #index < #size
BEGIN
-- Output as many UPDATE statements as required to append all the diagram binary
-- data, represented as hexadecimal strings
SELECT #line = #line + dbo.Tool_VarbinaryToVarchar_Text(SUBSTRING (definition, #index, #chunk),0),
#lineASC = #lineASC + dbo.Tool_VarbinaryToVarchar_Text(SUBSTRING (definition, #index, #chunk),1)
FROM dbo.sysdiagrams
WHERE diagram_id = #CurrentPos;
SET #index = #index + #chunk;
END
INSERT INTO #tblOut (diagramname, diagram_id, diagram_text, diagram_ASCII)
VALUES (#name, #diagram_id, #line, REPLACE(#lineASC,CHAR(13),''));
SELECT #CurrentPos = MIN(diagram_id)
FROM dbo.sysdiagrams
WHERE diagram_id > #CurrentPos;
END
RETURN;
END
After that you can run:
SELECT *
FROM [dbo].[fnTool_ScriptDiagram2005_Text] ()
WHERE diagram_ASCII LIKE '%TableToFind%'
For example I have created diagram TestDiagram with 2 tables named whatever and IE_Stat. In return query:
Root EntrypfoBCompObj_ !"#$%&'()*+,-.123456789:(}5n]4o[\0V?[?i???V?[?i??T,,,4") -bH''Uu94941#xV4XdboIE_StatMicrosoft DDS Form 2.0Embedded Object9q&sch_labels_visibled(ActiveTableViewMode1 TableViewMode:0:4,0,28DdsStreamSchema UDV Default&/DSREF-SCHEMA-CONTENTS,0Schema UDV Default Post V66;4,0,2310,1,1890,5,1260 TableViewMode:12,0,284,0,2805 TableViewMode:22,0,284,0,2310 TableViewMode:32,0,284,0,2310 TableViewMode:4>4,0,284,0,2310,12,2730,11,1680(ActiveTableViewMode1 TableViewMode:0:4,0,284,0,2310,1,1890,5,1260 TableViewMode:12,0,284,0,2805 TableViewMode:22,0,284,0,2310 TableViewMode:32,0,284,0,2310 TableViewMode:4>4,0,284,0,2310,12,2730,11,1680NaQW9 LHEData Source=********;Initial Catalog=test;Integrated Security=True;MultipleActiveResultSets=False;TrustServerCertificate=True;Packet Size=4096;Application Name="Microsoft SQL Server Management Studio"TestDiagram&whateverdbo$IE_StatdbokE7d2pN{1634CDD7-0888-42E3-9FA2-B6D32563B91D}bR
you can see both table names.

Why do I have two different return values from the queries in T-SQL

Hello I wonder why I have 2 different return Values.
Here is the first query:
declare #currentcolumn_val varchar
declare #start integer
set #currentcolumn_val = 'state_val'
set #start =1
select #currentcolumn_val from z_skm where id = #start
the returned value is just "s"
Here is the second Query which gives the correct return value:
select state_val from z_skm where id = 1
This query gives me exactly what it should.
I hope you guys can help.
Cheers steven
Your first query is returning a constant. The second is returning the value of the column.
You are returning 's' instead of 'state_val' because of the declaration:
declare #currentcolumn_val varchar;
You have no length on varchar() and in this context, it defaults to a length of 1. Always use length with varchar() in SQL Server.
If you want the column to be dynamic, you need to use dynamic SQL:
declare #currentcolumn_val nvarchar(255);
declare #start integer;
declare #sql nvarchar(max) = 'select #currentcolumn_val from z_skm where id = #start';
set #sql = replace(#sql, '#currentcolumn_val', #currentcolumn_val);
exec sp_executesql #sql, N'#start int', #start = #start;
You can pass a parameter as an argument, but not a column or table name.
You have declared #currentcolumn_val simply as varchar, which defaults to a length of 1.
if you replace it with declare #currentcolumn_val varchar(10) you will see the whole value
First you haven't given the #currentcolumn_val parameter a size so it is equivalent to a VARCHAR(1). This means that this:
set #currentcolumn_val = 'state_val'
Is the essentially the same as:
set #currentcolumn_val = 's'
Then in your SELECT you are returning the value of that variable, not a column from the table.

SQL Server Parse Key Value from text

i am a novice programmer in sql.
I want to grab some key value pairs from the text in sql column
e.g.
some text[Key1=Val1]some text[Key2=Val2][Key3=Val3]some text
i want a function which takes Keyname as input & returns the value related with it if found.
GetValueFmKey('Key1')
should return Val1 and like on.
Note: the specified values are in text it may have pre or post text exists.
Assumptions:
The square brackets [] are included as part of the text
You can use a stored procedure (not sure if you mean SQL Function or a subroutine, i.e. stored proc.
Place the following code in a stored procedure.
Have it's parameter use my #Param and remove the #Param declaration and SET value
DECLARE #Param VARCHAR(255) --Remove this
SET #Param = 'Key1' --Remove this
DECLARE #KeyStart SMALLINT
DECLARE #ValueStart SMALLINT
DECLARE #ValueEnd SMALLINT
SELECT #KeyStart = CHARINDEX(#Param, Col2)
FROM Table1
WHERE Col1 = 1;
SET #ValueStart = #KeyStart + LEN(#Param) + 1
SELECT #ValueEnd = CHARINDEX(']', Col2, #KeyStart)
FROM Table1
WHERE Col1 = 1;
SELECT SUBSTRING(Col2, #ValueStart, #ValueEnd - #ValueStart)
FROM Table1
WHERE Col1 = 1
Use following function:
ALTER FUNCTION dbo.GetValueFmKey(#text NVARCHAR(1000), #Key NVARCHAR(100))
RETURNS NVARCHAR(100)
AS BEGIN
SET #key = '['+#key + '='
IF (CHARINDEX(#Key,#text)=0) RETURN ''
SET #text = SUBSTRING(#text,CHARINDEX(#Key,#text)+LEN(#Key), LEN(#text))
RETURN LEFT(#text,CHARINDEX(']',#text)-1)
END
GO
For Example:
SELECT dbo.GetValueFmKey('text[Key2=Val2][Key3=Val3]','Key2')

how to assign NULL type for int type in sql server

Follow my code
begin
declare #Iorder int
set #Iorder=0
declare #no int
set #no=(select MAX(IOrder) from Team)
if #no=NULL
set #Iorder=1
else
begin
set #Iorder=(select MAX(IOrder) from Team)
set #Iorder=#Iorder+1
end
end
if in Team table has no row select MAX(IOrder) from Team statement return NULL value so statement if #no=NULL is not correct because #no is int type then SQL Server return a error Null value is eliminated by an aggregate or other SET operation.
So how to fix it?
Test using is null instead.
begin
declare #Iorder int
set #Iorder=0
declare #no int
set #no=(select MAX(IOrder) from Team)
if #no is null
set #Iorder=1
else
begin
set #Iorder=(select MAX(IOrder) from Team)
set #Iorder=#Iorder+1
end
end
Your code can be rewritten using isnull() instead.
declare #Iorder int
select #Iorder = 1 + isnull(max(IOrder), 0) from Team
You can simply do this all in a short form.
Try this:
begin
declare #Iorder int
SELECT #Iorder = ISNULL(MAX(IOrder),0)+1 FROM Team
end
Explanation:
#Iorder will be 1 (i.e., 0+1) if MAX(IOrder) is NULL.
Otherwise, #Iorder will be MAX(IOrder)+1.
Use SELECT ISNULL(MAX(IOrder),0) FROM Team (Returns 0 in case of null) and remove the if else to check null values, SELECT ISNULL(MAX(IOrder),0) + 1 FROM Team in case you want incremented value