Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 days ago.
Improve this question
I want to randomly choose a row in a column and change the values. I’m not too sure where Rand function goes.
To be more specific, I have a table with names in it but I want to randomly select one of the names from the first name column and change it to a different name of my choosing using the UPDATE and RAND() function and it can't be NEWID(). What parameters do I need inside the parenthesis as well?
I am using SQL Server Express
I tried starting the code out with
UPDATE table name
SET column name1 = ‘new name’, column name2 = 'new name 2'
WHERE column name = (SELECT RAND()(column name-column name)+column name
from table name);
We can use NEWID() to fetch a random row, see the documentation, especially part D.
Here an example how to use it:
Create a table with some sample data:
CREATE TABLE yourtable (yourcolumn varchar(100));
INSERT INTO yourtable VALUES ('A'),('B'),('C'),('D'),('E');
Update one randow row of this table:
UPDATE yourtable SET yourcolumn = 'HelloWorld'
WHERE yourcolumn = (SELECT TOP 1 yourcolumn FROM yourtable ORDER BY NEWID());
If we want to set the value of that column in one random row to a random existing value of another row rather than to a hardcoded string, we could use NEWID() two times, something like this:
UPDATE yourtable SET yourcolumn =
(SELECT TOP 1 yourcolumn FROM yourtable ORDER BY NEWID())
WHERE yourcolumn = (SELECT TOP 1 yourcolumn FROM yourtable ORDER BY NEWID())
Try out here
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 days ago.
Improve this question
Example:
SubNetwork=ONRM_ROOT_MO,SubNetwork=RadioNode,MeContext=BAS917L
I want to extract only RadioNode
SubNetwork=ONRM_ROOT_MO,SubNetwork=GALRNC1,MeContext=BAT045W
I want to extract only GALRNC1.
You can do it using SUBSTRING and LEFT and charindex
select LEFT(sub1, CHARINDEX(',MeContext', sub1) - 1)
from (
select
SUBSTRING(column1, charindex('SubNetwork=', column1, 2) + LEN('SubNetwork='), 20) sub1
from mytable
) as s
charindex to get the position of your word in this case it is SubNetwork=.
SUBSTRING to Extract characters from a string.
LEFT to Extract characters from a string (starting from left).
Demo here
Please try the following solution.
It is using JSON and will work starting from SQL Server 2016 onwards.
SQL
-- DDL and sample data population, start
DECLARE #tbl TABLE (id INT IDENTITY PRIMARY KEY, tokens NVARCHAR(1024));
INSERT #tbl (tokens) VALUES
(N'SubNetwork=ONRM_ROOT_MO,SubNetwork=RadioNode,MeContext=BAS917L'),
(N'SubNetwork=ONRM_ROOT_MO,SubNetwork=GALRNC1,MeContext=BAT045W');
-- DDL and sample data population, end
SELECT t.*
, SubNetwork = JSON_VALUE(j,'$.SubNetwork')
FROM #tbl AS t
CROSS APPLY (SELECT '{"' + REPLACE(REPLACE(STRING_ESCAPE('~'+tokens,'json')
,',','","')
,'=','":"') + '"}'
) AS t1(j);;
Output
id
tokens
SubNetwork
1
SubNetwork=ONRM_ROOT_MO,SubNetwork=RadioNode,MeContext=BAS917L
RadioNode
2
SubNetwork=ONRM_ROOT_MO,SubNetwork=GALRNC1,MeContext=BAT045W
GALRNC1
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 months ago.
Improve this question
SELECT *
FROM table1
WHERE (#Id IS NULL
OR (a.ID = #Id)
OR (SELECT * FROM Table2 WHERE TestID = #Id) // How to check multiple values here
The above query works fine when TestID has single record. But when more than 1 record present in TestID column, I am trying to implement and not got exact solution.
How to confirm #Id value present in TestId column?
Could you please assist me on this? Thank you
It looks like you need exists
or exists (
SELECT * FROM Table2 WHERE TestID = #Id
)
Use top 1 before * from this way you will always get a single row in case there are multiple rows for the same #ID.
SELECT top 1 * FROM Table2 WHERE TestID = #Id
Though I am not sure how this line works in where clause as it does not return any boolean
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
create table t1 (col1 int);
Leave the table empty.
select isnull(col1,0) from t1;
I want to replace null with zeros in the above case. However, ISNULL() does not work if there are no records in the table. How can I get around this?
Maybe you can first test if the table is empty:
IF NOT EXISTS (select * from t1)
SELECT 0
ELSE select coalesce(col1,0) from t1;
Anyway, you should use COALESCE instead of ISNULL because it is standard SQL.
In case if you want to replace non existing value then surround another null check of mentioned select statement. like this
ISNULL(select isnull(col1,0) from t1,0)
COALESCE(col1, 0)
will give you the first non-NULL value from the list, which is
col1 if col1 does not contain NULL
0 if col1 contains NULL.
If no record exists in the table , your query returns EMPTY not NULL .
You can transform the EMPTY value into a NULL value and then switch it to 0 like this :
SELECT ISNULL((SELECT col1 FROM tl),0) AS col1;
When I want to return exactly one row from a table that might be empty or have an arbitrary number of rows, then I often use aggregation:
select coalesce(max(col1), 0)
from t1;
This is guaranteed to return exactly one row. It is unclear what you want when the table is not empty, however.
If you absolutely must have a value returned for an empty table, maybe something like:
if ((select COUNT(*) from t1) = 0)
begin
select 0 as col1;
end
else
begin
select isnull(col1,0) as col1 from t1;
end
The left join will get a hard coded table, OneZero, even with no rows in t1.
select isnull(t1.col1, OneZero.zero)
from ( values(0) ) as OneZero (zero)
left join t1
on 1 = 1
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have 2 tables: MainTable and ControlTable.
I want to write a query that builds a string representing a file path.
File path will be built dynamically depending on a query result between two tables.
Main table has the following columns:
ControlNumber
CustomerID
CustomerStatement
The Control table has only one column: ControlNumber
I need to write a query that checks if Main table has a ControlNumber defined in Control Table.
If there is a match, I append \FolderA to my FilePath
If no match, I append \FolderB
Ending result will be something like this:
C:\Customers\FolderA or C:\Customers\FolderB
I suspect I need to use left join
How can I do that?
You're right that you want a left join. Combine that with a case...when expression to determine the value:
select
*,
case
when Control.ControlNumber is not null
then '\FolderA'
else '\FolderB'
end as FilePath
from main
left join control on main.ControlNumber = control.ControlNumber
It's not clear where the rest of the path comes from; maybe it's static and you want to concatenate it with the value from the case expression:
'c:\customers' + -- or concat() or || depending on sql dialect
case when Control.ControlNumber is not null then '\FolderA' else '\FolderB' end as FilePath
SELECT 'C:\' || CustomerID || '\FolderA'
FROM MainTable
WHERE EXISTS
( SELECT 1 FROM ControlNumber WHERE ControlTable.ControlNumber = MainTable.CustomerID )
UNION
SELECT 'C:\' || CustomerID || '\FolderB'
FROM MainTable
WHERE NOT EXISTS
( SELECT 1 FROM ControlTable WHERE ControlTable.ControlNumber = MainTable.ControlNumber)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I want to use empty value in an IN clause. But following queries don't work identically.
SELECT * from tblTest WHERE colName IN ( '')
SELECT * from tblTest WHERE colName IN (SELECT '''''')
The first works fine but the second has no error but gives empty result.
It's because SELECT '''''' will return you '' and try to compare your values to it, which is not an empty string.
Anyway, it's not quite clear what you're trying to achieve.
That's pretty clear: you want the rows where the column contains an empty string. But if you compare with (select '''''') you dont select an empty string! You select a string that looks like this: ''
This works:
SELECT * from tblTest WHERE colName IN (SELECT '')