How to compare multiple parameters of a row column value? - sql-server-2008

how to write query for following request?
my table:
id designation
1 developer,tester,projectlead
1 developer
1 techlead
if id=1,designation="'developer'"
Then need to first,second records.Because 2 rows are having venkat.
if id=1,designation="'developer','techlead'" then need to get 3 records as result.
i wrote one service for inserting records to that table .so that i am maintaining one table to store all designation with same column with comas.
By using service if user pass id=1 designation="'developer','techlead'" then need to pull the above 3 records.so that i am maintaining only one table to save all designations
SP:
ALTER PROCEDURE [dbo].[usp_GetDevices]
#id INT,
#designation NVARCHAR (MAX)
AS
BEGIN
declare #idsplat varchar(MAX)
set #idsplat = #UserIds
create table #u1 (id1 varchar(MAX))
set #idsplat = 'insert #u1 select ' + replace(#idsplat, ',', ' union select ')
exec(#idsplat)
Select
id FROM dbo.DevicesList WHERE id=#id AND designation IN (select id1 from #u1)
END

You need to use the boolean operators AND and OR in conjunction with LIKE:
IF empid = 1 AND (empname LIKE '%venkat%' OR empname LIKE '%vasu%')
The above example will return all rows with empid equals 1 and empname containing venkat or vasu.
Apparently you need to create that query based on the input from user, this is just an example of how the finally query should look like.
Edit: Trying to do this within SqlServer can be quite hard so you should really change your approach on how you call the stored procedure. If you can't do this then you could try and split your designation parameter on , (the answers to this question show several ways of how to do this) and insert the values into a temporary table. Then you can JOIN on this temporary table with LIKE as described in this article.

Related

SQL Trigger: New row :tableA to new col in :tableB

I have a database with a couple of tables. I need to add a column in one table after the insertion of a new row in another table.
Table A: id | Type | Category | ShortDesc | LongDesc | Active
Row 1 int(11), varchar, varchar,varchar,varchar,int
Row 2
Row 3
Table B: id | Row1-ShortDesc | Row2-ShortDesc | Row3-ShortDesc
Row 1 int(11), tiny(1), tiny(1), tiny(1) etc...
Row 2
Row 3
When I occasionally add a new row (item) to TableA, I want a new column in TableB. TableA is a long evolving collection. A Row in TableA can not be removed for obvious legacy reasons.
So when I insert a row to TableA I need to have another column inserted/appended into TableB.
Any help would be appreciated.
TIA.
Answer derived from training in SQL
I was finally able to derive and create my trigger solution utilizing a class in SQL Server at MAX TRAINING in CINCINNATI OHIO.
--SQL CODE
-- Create a table called TableA that just holds some data for the trigger
-- This table has a primary Key seeded with 1 and incremented by 1
CREATE TABLE TableA(
id int identity(1,1) PRIMARY KEY,
name varchar(60) NOT NULL,
shortDesc varchar(60) NOT NULL,
longDesc varchar(60) NOT NULL,
bigDesc TEXT NOT NULL
)
GO
-- Create a table TableB that only has a ID column. ID as a primary key seeded with 1, incremented by 1
CREATE TABLE TableB(
id int identity(1,1) PRIMARY KEY
)
GO
-- Just to see the two tables with nothing in it.
select * from TableA
select * from TableB
GO
-- The actual trigger in TableA based upon an insert
CREATE TRIGGER TR_myInserCol
ON TableA
AFTER INSERT
AS
BEGIN
-- Don't count the trigger events
SET NOCOUNT ON;
-- Because we are making strings we declare some variables
DECLARE #newcol as varchar(60);
DECLARE #lastRow as int;
DECLARE #sql as varchar(MAX);
-- Now fill the variables
-- make sure we are looking at the last, freshly inserted row
SET #lastRow = (SELECT COUNT(*) FROM TableA);
-- Make a SELECT statement for the last row
SET #newcol = (SELECT shortDesc FROM TableA WHERE id = #lastRow);
-- Adds a new column in TableB is inserted based on a
-- TableA.shortDesc as the name of the new column.
-- You can use any row data you want but spaces and
-- special characters will require quotes around the field.
SET #sql = ('ALTER TABLE TableB ADD ' + #newcol + ' char(99)');
-- And run the SQL statement as a combined string
exec(#sql);
END;
GO
--Insert a new rows into TableA
--The trigger will fire and add a column in TableB
INSERT INTO TableA
(name,shortDesc,longDesc,bigDesc)
VALUES ('attract','Attraction','Attractions','Places to go see and have
fun');
GO
INSERT INTO TableA
(name,shortDesc,longDesc,bigDesc)
VALUES ('camp','Camp','CAMP GROUND','Great place to sleep next to a creek');
GO
(name,shortDesc,longDesc,bigDesc)
VALUES ('fuel','GasStation','Fueling Depot','Get gas and go');
GO
INSERT INTO TableA
(name,shortDesc,longDesc,bigDesc)
VALUES ('petstore','PetStore','Pet Store','Get a friend');
GO
-- See the newly created rows in TableA and the new Columns created in TableB
select * from TableA
select * from TableB
GO
-- Do not execute unless you want to delete the newly created tables.
-- Use this to delete your tables
-- Clean up your work space so you can make changes and try again.
DROP TABLE TableA;
DROP TABLE TableB;
GO
Thanks again to those that tried to help me out. And yes, I still understand this may not be the best solution but for me this works as I will only insert rows in TableA maybe a couple of times a year and will more than likely max out with less than 300 rows over the next several years as the data I am working with doesn't change that frequently and have a single row to access with a single bit (T/F) allows me to now quickly assign TableB's to locations and people for their search criteria and to generate a nice SQL query string without multiple reads across potentially several pages. Thanks again!
And if someone wants to add or modify what I have done, I'm all ears. It's all about learning and sharing.
Michael

Count for separated by special symbol String in each row without using any other table or Stored Procedure

I have to get count of each value separated by ## without
using Any table or stored procedure . i have to get count for each value repeated by
special symbol as per the given schema. I have tried alot but i want to make this result set without helping any reference table or stored procedure or temporary table.
Schema is like this :-
CREATE TABLE USER_TABLE (
id INT,
name VARCHAR(20));
INSERT INTO USER_TABLE VALUES
(1, 'A##B##C'),
(2, 'B##C'),
(3,'A'),
(4,'B##C');
Expected output is Like :-
Name COUNT
A 2
B 3
C 3
Try these query, may help you:
Select GROUP_CONCAT((name) SEPARATOR '#') as name, count(name) as count FROM your_table

Find Row Number of Record in MySQL

Suppose I have a table with one column - called 'person' that contains a list of names. I want to find a specific person based off his index.
I tried using a sql variable to track each column index but the issue is - is that if I have a table of 5 records this will always output the 5th record.
SET #row_num = 0; SELECT #row_num := #row_num + 1 as row1 ,person FROM table;
SELECT row1 from table WHERE person = 'name'
I would recommend changing your database to add a second column for row_id. This is a fairly common practice. Then you can just use
SELECT * from table WHERE row_id = 3;
This will return the third row.
Another best possible way would be by means of a TEMPORARY TABLE as explained below
create a temp table
create temporary table temptab(ID INT NOT NULL AUTO_INCREMENT,Person VARCHAR(30))
Then insert data to temp table as
insert into temptab(Person) select Person from mytable
Then select the specific index person name from temp table like
select Person from temptab where ID = 5

Replacing the single quotes for columns in select statement in SQL Server

I have 2 tables. In table1 I have some rows for persons like this:
PersonX - ID
PersonX - Name
PersonX - Address
PersonY - ID
PersonY - AGE
In 2nd table, above mentioned ID, NAME,ADDRESS,AGE will be columns. And we have detailed data of personX and PersonY here.
Now, main issue is in stored procedure, using cursor, I am storing table1 values ('ID', 'Name', ...) in a variable #Element.
Now I am using select statement in same cursor as below:
SELECT #Element From Table2
I need output of user details like his id, age, address etc. But instead I am getting output as 'ID', 'NAME', 'AGE' etc....
I found that this is because #Element is varchar and has string value, so select statement is executed as below:
SELECT 'ID' from table2.
but all I need is like below
SELECT ID FROM TABLE2
I used replace function its not working for me. Case function, I can't use it because we can't say what data is there for a person in table1. It varies. I need one dynamic statement which can be use for all records. instead of executing case for each record.
SELECT REPLACE(#Element,'''','')
FROM TABLE2
(Still getting 'ID' as output, instead of corresponding value in Table2)
Please help me in this. Hope you understand my explanation
You will need to use dynamic SQL to achieve this, for example:
CREATE TABLE Table1
(
ID INT
,Name VARCHAR(255)
,ADDRESS VARCHAR(255)
)
INSERT Table1 VALUES ('1','Joe Bloggs','Address 1')
INSERT Table1 VALUES ('2','Jane Doe','Address 2')
DECLARE #ColName VARCHAR(255) = 'ID'
DECLARE #SQL VARCHAR(MAX)
SET #SQL = 'SELECT '+#ColName+','+''''+#ColName+''' FROM TABLE1'
EXEC (#SQL)
In the first column that is returned, is the SQL you want to be able to execute, however in the 2nd column in my query, is what you're doing at the moment. As far as SQL is concerned, your variable is simply storing a value. It does not know you are referring to a column name which is why it simply returns the value.

Delete columns on couple of conditions

In a previous question I asked how I could sum up a total based on some conditions: Count total on couple of conditions
Suppose I have a table like this:
id col1 col2 col3
1 a 1 k1
2 a 2 k2
3 a -3 k3
4 b 3 k4
Now, when I get id=1, I want to delete all the rows where col1=a.
When I get id=4, I want to delete all the rows where col1=b.
How would I do this in SQL?
I tried based upon previous answer:
DELETE FROM table WHERE (col1) IN (SELECT col1 FROM table WHERE id = '1')
But that gave me an error: #1093 - You can't specify target table 'table' for update in FROM clause
This has been many times on stackowerflow, you cannot UPDATE/DELETE table with data from nested select on the same table. There're two ways to do this:
Load all data before (for example via php, sql procedure)
Create temporary table like the one you're using, clone data and use temporary table to select items
i have another suggested solution for this. What if you create a STORED PROCEDURE for this problem?
like this:
DELIMITER $$
CREATE PROCEDURE `DeleteRec`(IN xxx varchar(5))
BEGIN
DECLARE oID varchar(5);
SET oID := (SELECT col1 FROM table WHERE id = '1');
DELETE FROM table WHERE col1 = oID;
END$$
DELIMITER ;
do this helps you?